Php Slim not handle errors with the custom errorHandler

Viewed 1834

My custom error handler is not working with Slim 3 framework. Instead of getting a 500 error, I get a response with status 200 and the html error details are in the body.

Here is my minimal, verifiable and complete example:

$c = new \Slim\Container();
$c['errorHandler'] = function ($c) {
    return function($request, $response, $exception) use ($c) {
        return $c['response']->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write('Something went wrong!');
    };
};

$app = new \Slim\App($c);

$app->any('/foo', function($request, $response, $args) {
    $data = json_encode($request->nonExistingMethod()); // error!
    return $response->withJson($data);
});

$app->run();

How do I need to refactor this sample to make it work? I suspect it's related with the Fatal nature of the error. But in this case how to deal with that?

Reference: http://www.slimframework.com/docs/handlers/error.html

Edit 1

For use in an api style web application, the final solution I'm using with minor changes from the response of this question:

function checkForError() {
  $last = error_get_last();

  if ($last) {
    @header("HTTP/1.0 500 Internal Server Error");
    echo json_encode($last); // optional, includes error details in json format
  }
}

error_reporting(0);
register_shutdown_function('checkForError');
1 Answers
Related