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
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;

public function onKernelException(GetResponseForExceptionEvent $event)
{
    $exception = $event->getException();
    // 500 is the original status code; but the end user will get a 404
    $response = new Response('...', 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
public function onKernelException(GetResponseForExceptionEvent $event)
{
    $exception = $event->getException();
    $response = new Response('...', 404);

    // ...

    $event->allowCustomResponseCode();
    $event->setResponse($response);
}
Published in #Living on the edge