diff --git a/src/Handler/ExceptionHandler.php b/src/Handler/ExceptionHandler.php index d5c082e..05d681d 100644 --- a/src/Handler/ExceptionHandler.php +++ b/src/Handler/ExceptionHandler.php @@ -71,7 +71,12 @@ public function __invoke( $response = $response->withHeader('Content-Type', $type); try { - $response = $response->withStatus($e->getCode()); + if (method_exists($e, 'getHttpStatus')) { + $code = $e->getHttpStatus(); + } else { + $code = $e->getCode(); + } + $response = $response->withStatus($code); } catch (InvalidArgumentException $_) { // Exception did not contain a valid code $response = $response->withStatus(500); diff --git a/tests/Handler/ExceptionHandlerTest.php b/tests/Handler/ExceptionHandlerTest.php index df69e0b..0999f35 100644 --- a/tests/Handler/ExceptionHandlerTest.php +++ b/tests/Handler/ExceptionHandlerTest.php @@ -63,6 +63,17 @@ public function testHandle($mime) $this->assertEquals($mime, $response->getHeaderLine('Content-Type')); } + public function testHandleWithHttpStatusCode() + { + $request = new ServerRequest; + + $response = $this->execute(function ($request, $response) { + throw new ExceptionWithHttpStatusCode('foo'); + }, $request); + + $this->assertEquals(400, $response->getStatusCode()); + } + public function testNotFound() { $response = $this->execute(function ($request, $response) { @@ -82,3 +93,11 @@ public function testMethodNotAllowed() $this->assertEquals('GET,PUT', $response->getHeaderLine('Allow')); } } + +class ExceptionWithHttpStatusCode extends \Exception +{ + public function getHttpStatus() + { + return 400; + } +}