Skip to content

Update docs for setting custom response code in exception handler #6948

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions reference/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -243,17 +243,20 @@ and set a new ``Exception`` object, or do nothing::

As Symfony ensures that the Response status code is set to the most
appropriate one depending on the exception, setting the status on the
response won't work. If you want to overwrite the status code (which you
should not without a good reason), set the ``X-Status-Code`` header::

$response = new Response(
'Error',
404, // this status code will be ignored
array(
'X-Status-Code' => 200 // this status code will actually be sent to the client
)
);
response alone won't work. If you want to overwrite the status code
(which you should not without a good reason), call
``GetResponseForExceptionEvent::allowSuccessfulResponse()`` and
then set the status code on the response as normal. The kernel will
now use your status code when sending the response to the client::

$event->allowSuccessfulResponse();
$response = new Response('No Content', 204);
$event->setResponse($response);

The status code sent to the client in the above example will be 204.
If we were to omit the call to ``$event->allowSuccessfulResponse()``
then the kernel would set an appropriate status code based on the type
of exception thrown.
.. seealso::

Read more on the :ref:`kernel.exception event <component-http-kernel-kernel-exception>`.
Expand Down