Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3057

New in Symfony 3.3: Deprecated X-Status-Code

$
0
0
James Halsall

Contributed by
James Halsall
in #19822.

Sometimes, when handling exceptions in your Symfony applications, you may want to change the original HTTP response status code (for example to return a 404 error instead of the original 5xx code).

Of course you should not do this without a good reason, but Symfony lets you do it by setting a special X-Status-Code HTTP header:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
useSymfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;useSymfony\Component\HttpFoundation\Response;publicfunctiononKernelException(GetResponseForExceptionEvent$event){$exception=$event->getException();// 500 is the original status code; but the end user will get a 404$response=newResponse('...',500,['X-Status-Code'=>404]);// ...$event->setResponse($response);}

The X-Status-Code header is not a standard HTTP feature, so it has always bugged us. In Symfony 3.3, we finally decided to get rid of it and stick to the standard way of dealing with HTTP responses.

Instead of the X-Status-Code header, now you can set the status code as usual in the response and then, call the new allowCustomResponseCode() method to tell the Kernel to use the response code set on the event's response object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
publicfunctiononKernelException(GetResponseForExceptionEvent$event){$exception=$event->getException();$response=newResponse('...',404);// ...$event->allowCustomResponseCode();$event->setResponse($response);}

Be trained by Symfony experts - 2017-03-22 Paris - 2017-04-03 Paris - 2017-04-03 Paris

Viewing all articles
Browse latest Browse all 3057

Trending Articles