Skip to content

Commit 788e5eb

Browse files
committed
[HttpKernel] added a way to override the default response status code when handling an exception (closes #5043)
1 parent a172a81 commit 788e5eb

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/Symfony/Component/HttpKernel/HttpKernel.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,13 @@ private function handleException(\Exception $e, $request, $type)
194194

195195
$response = $event->getResponse();
196196

197-
// ensure that we actually have an error response
198-
if (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
197+
// the developer asked for a specific status code
198+
if ($response->headers->has('X-Status-Code')) {
199+
$response->setStatusCode($response->headers->get('X-Status-Code'));
200+
201+
$response->headers->remove('X-Status-Code');
202+
} elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
203+
// ensure that we actually have an error response
199204
if ($e instanceof HttpExceptionInterface) {
200205
// keep the HTTP status code and headers
201206
$response->setStatusCode($e->getStatusCode());

src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,33 @@ public function testHandleHttpException()
9696
$this->assertEquals('POST', $response->headers->get('Allow'));
9797
}
9898

99+
/**
100+
* @dataProvider getStatusCodes
101+
*/
102+
public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
103+
{
104+
$dispatcher = new EventDispatcher();
105+
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) use ($responseStatusCode, $expectedStatusCode) {
106+
$event->setResponse(new Response('', $responseStatusCode, array('X-Status-Code' => $expectedStatusCode)));
107+
});
108+
109+
$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException(); }));
110+
$response = $kernel->handle(new Request());
111+
112+
$this->assertEquals($expectedStatusCode, $response->getStatusCode());
113+
$this->assertFalse($response->headers->has('X-Status-Code'));
114+
}
115+
116+
public function getStatusCodes()
117+
{
118+
return array(
119+
array(200, 404),
120+
array(404, 200),
121+
array(301, 200),
122+
array(500, 200),
123+
);
124+
}
125+
99126
public function testHandleWhenAListenerReturnsAResponse()
100127
{
101128
$dispatcher = new EventDispatcher();

0 commit comments

Comments
 (0)