Skip to content

Commit

Permalink
[HttpKernel] added a way to override the default response status code…
Browse files Browse the repository at this point in the history
… when handling an exception (closes #5043)
  • Loading branch information
fabpot committed Jul 31, 2012
1 parent a172a81 commit 788e5eb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Symfony/Component/HttpKernel/HttpKernel.php
Expand Up @@ -194,8 +194,13 @@ private function handleException(\Exception $e, $request, $type)

$response = $event->getResponse();

// ensure that we actually have an error response
if (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
// the developer asked for a specific status code
if ($response->headers->has('X-Status-Code')) {
$response->setStatusCode($response->headers->get('X-Status-Code'));

$response->headers->remove('X-Status-Code');
} elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
// ensure that we actually have an error response
if ($e instanceof HttpExceptionInterface) {
// keep the HTTP status code and headers
$response->setStatusCode($e->getStatusCode());
Expand Down
27 changes: 27 additions & 0 deletions src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php
Expand Up @@ -96,6 +96,33 @@ public function testHandleHttpException()
$this->assertEquals('POST', $response->headers->get('Allow'));
}

/**
* @dataProvider getStatusCodes
*/
public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
{
$dispatcher = new EventDispatcher();
$dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) use ($responseStatusCode, $expectedStatusCode) {
$event->setResponse(new Response('', $responseStatusCode, array('X-Status-Code' => $expectedStatusCode)));
});

$kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException(); }));
$response = $kernel->handle(new Request());

$this->assertEquals($expectedStatusCode, $response->getStatusCode());
$this->assertFalse($response->headers->has('X-Status-Code'));
}

public function getStatusCodes()
{
return array(
array(200, 404),
array(404, 200),
array(301, 200),
array(500, 200),
);
}

public function testHandleWhenAListenerReturnsAResponse()
{
$dispatcher = new EventDispatcher();
Expand Down

0 comments on commit 788e5eb

Please sign in to comment.