diff --git a/src/Symfony/Component/ErrorHandler/ErrorHandler.php b/src/Symfony/Component/ErrorHandler/ErrorHandler.php index 5493e61a63..2064427f0a 100644 --- a/src/Symfony/Component/ErrorHandler/ErrorHandler.php +++ b/src/Symfony/Component/ErrorHandler/ErrorHandler.php @@ -592,7 +592,11 @@ class ErrorHandler } } $exceptionHandler = $this->exceptionHandler; - $this->exceptionHandler = null; + if ((!\is_array($exceptionHandler) || !$exceptionHandler[0] instanceof self || 'sendPhpResponse' !== $exceptionHandler[1]) && !\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + $this->exceptionHandler = [$this, 'sendPhpResponse']; + } else { + $this->exceptionHandler = null; + } try { if (null !== $exceptionHandler) { return $exceptionHandler($exception); @@ -696,18 +700,28 @@ class ErrorHandler private function sendPhpResponse(\Throwable $exception) { $charset = ini_get('default_charset') ?: 'UTF-8'; - - if (!headers_sent()) { - header('HTTP/1.0 500'); - header(sprintf('Content-Type: text/html; charset=%s', $charset)); - } + $statusCode = 500; + $headers = []; if (class_exists(HtmlErrorRenderer::class)) { - echo (new HtmlErrorRenderer(true))->render(FlattenException::createFromThrowable($exception)); + $exception = FlattenException::createFromThrowable($exception); + $statusCode = $exception->getStatusCode(); + $headers = $exception->getHeaders(); + $response = (new HtmlErrorRenderer(true))->render($exception); } else { $message = htmlspecialchars($exception->getMessage(), ENT_COMPAT | ENT_SUBSTITUTE, $charset); - echo sprintf('%s', $charset, $message); + $response = sprintf('%s', $charset, $message); } + + if (!headers_sent()) { + header(sprintf('HTTP/1.0 %s', $statusCode)); + foreach ($headers as $name => $value) { + header($name.': '.$value, false); + } + header('Content-Type: text/html; charset='.$charset); + } + + echo $response; } /** diff --git a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php index 6f8f56ef69..b536627a02 100644 --- a/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php +++ b/src/Symfony/Component/ErrorHandler/Tests/ErrorHandlerTest.php @@ -557,6 +557,18 @@ class ErrorHandlerTest extends TestCase $handler->handleException(new \Exception()); } + public function testSendPhpResponse() + { + $handler = new ErrorHandler(); + $handler->setExceptionHandler([$handler, 'sendPhpResponse']); + + ob_start(); + $handler->handleException(new \RuntimeException('Class Foo not found')); + $response = ob_get_clean(); + + self::assertStringContainsString('Class Foo not found', $response); + } + /** * @dataProvider errorHandlerWhenLoggingProvider */