Quantcast
Channel: Slim Framework – Rob Allen's DevNotes
Viewing all articles
Browse latest Browse all 38

Improved error handling in Slim 3 RC1

$
0
0

From RC1 of Slim 3, we have improved our error handling. We've always had error handling for HTML so that when an exception occurs, you get a nice error page that looks like this:

Slim3 error page

However, if you're writing an API that sends and expects JSON, then it still sends back HTML:

Slim3 old json error

At least we set the right Content-Type and status code!

However, this isn't really good enough. We should send back JSON if the client has asked for JSON. Until RC1, the only way to do this was to register your own error handler:

$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
  return function ($request, $response, $exception) use ($c) {
    $data = [
      'code' => $exception->getCode(),
      'message' => $exception->getMessage(),
      'file' => $exception->getFile(),
      'line' => $exception->getLine(),
      'trace' => explode("\n", $exception->getTraceAsString()),
    ];

    return $c->get('response')->withStatus(500)
             ->withHeader('Content-Type', 'application/json')
             ->write(json_encode($data));
  };
};

which provides the correct output:

Slim 3 custom json error

However, we can do better than this and do it for you. Starting with RC1, Slim will now output JSON (or XML) when an error occurs if the client's Accept header is applcation/json (or application/xml) and it will also provide all the previous exception too. This is much nicer and also works for the two other error handlers: notFound and notAllowed.

Slim 3 rc1 error json

Finally, Note that you should never use our default errorHandler in production as it leaks too much data! We'll try and fix this before 3.0 final, though.


Viewing all articles
Browse latest Browse all 38

Trending Articles