Max Bündchen
Max Bündchen

Reputation: 1362

Php Slim not handle errors with the custom errorHandler

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');

Upvotes: 4

Views: 2006

Answers (1)

wodka
wodka

Reputation: 1380

you cannot catch all errors like this

there is however one way to catch all except memory errors (or only those that tried to allocate more than your error handler needs)

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

  if ($last) {
    @header("HTTP/1.0 500 Internal Server Error");
    echo 'we failed... sry';
  }
}

register_shutdown_function('checkForError');

updated with 500 status header

Upvotes: 3

Related Questions