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:
However, if you're writing an API that sends and expects JSON, then it still sends back HTML:
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:
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.
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.