Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1d59c3c

Browse files
author
James Halsall
committed
Update docs for setting custom response code in exception handler
1 parent f78d06b commit 1d59c3c

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

reference/events.rst

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -243,17 +243,19 @@ and set a new ``Exception`` object, or do nothing::
243243

244244
As Symfony ensures that the Response status code is set to the most
245245
appropriate one depending on the exception, setting the status on the
246-
response won't work. If you want to overwrite the status code (which you
247-
should not without a good reason), set the ``X-Status-Code`` header::
248-
249-
$response = new Response(
250-
'Error',
251-
404, // this status code will be ignored
252-
array(
253-
'X-Status-Code' => 200 // this status code will actually be sent to the client
254-
)
255-
);
256-
246+
response alone won't work. If you want to overwrite the status code
247+
(which you should not without a good reason), call
248+
``GetResponseForExceptionEvent::setAllowSuccessfulResponse(true)`` and
249+
then set the status code on the response as normal. The kernel will
250+
now use your status code when sending the response to the client::
251+
252+
$event->setAllowSuccessfulResponse(true);
253+
$response = new Response('No Content', 204);
254+
255+
The status code sent to the client in the above example will be 204.
256+
If we were to omit the call to ``$event->setAllowSuccessfulResponse()``
257+
then the kernel would set an appropriate status code based on the type
258+
of exception thrown.
257259
.. seealso::
258260

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

0 commit comments

Comments
 (0)