Skip to content

Commit

Permalink
Instead of triggering a fatal error, modify the response.
Browse files Browse the repository at this point in the history
Modify the response with a text response and log an error when rendering
an error page.
  • Loading branch information
markstory committed Apr 29, 2016
1 parent fbf3de3 commit 50dabae
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
12 changes: 9 additions & 3 deletions src/Http/Middleware/ErrorHandlerMiddleware.php
Expand Up @@ -15,8 +15,8 @@
namespace Cake\Http\Middleware;

use Cake\Core\App;
use Cake\Log\Log;
use Cake\Http\ResponseTransformer;
use Exception;

/**
* Error handling middleware.
Expand Down Expand Up @@ -68,14 +68,19 @@ public function handleException($exception, $request, $response)
try {
$response = $renderer->render();
return ResponseTransformer::toPsr($response);
} catch (Exception $e) {
} catch (\Exception $e) {
$message = sprintf(
"[%s] %s\n%s", // Keeping same message format
get_class($e),
$e->getMessage(),
$e->getTraceAsString()
);
trigger_error($message, E_USER_ERROR);
Log::error($message);

$body = $response->getBody();
$body->write('An Internal Server Error Occurred');
$response = $response->withStatus(500)
->withBody($body);
}
return $response;
}
Expand All @@ -85,6 +90,7 @@ public function handleException($exception, $request, $response)
*
* @param \Exception $exception The exception being rendered.
* @return \Cake\Error\BaseErrorHandler The exception renderer.
* @throws \Exception When the renderer class cannot be found.
*/
protected function getRenderer($exception)
{
Expand Down
5 changes: 3 additions & 2 deletions tests/TestCase/Http/Middleware/ErrorHandlerMiddlewareTest.php
Expand Up @@ -114,7 +114,6 @@ public function testHandleException()
/**
* Test handling an error and having rendering fail.
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testHandleExceptionRenderingFails()
Expand All @@ -135,6 +134,8 @@ public function testHandleExceptionRenderingFails()
$next = function ($req, $res) {
throw new \Cake\Network\Exception\ServiceUnavailableException('whoops');
};
$middleware($request, $response, $next);
$response = $middleware($request, $response, $next);
$this->assertEquals(500, $response->getStatusCode());
$this->assertEquals('An Internal Server Error Occurred', '' . $response->getBody());
}
}

0 comments on commit 50dabae

Please sign in to comment.