Skip to content

Commit d825c4a

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

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

reference/events.rst

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -243,17 +243,20 @@ 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-
);
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::allowSuccessfulResponse()`` 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->allowSuccessfulResponse();
253+
$response = new Response('No Content', 204);
254+
$event->setResponse($response);
256255

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

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

0 commit comments

Comments
 (0)