Hi all, I'm developing a REST API using Transformers and JSON responses.
I want to render proper error messages as jsonapi.org recommended.
My app/Exceptions/Handler.php render() method:
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
$status = 500;
$title = 'General error';
$detail = 'Sorry, something unthinkable happened now';
switch($e){
case ($e instanceof NotFoundHttpException):
$status = 404;
$title = 'The requested resource has not been found';
$detail = '';
break;
case ($e instanceof MethodNotAllowedHttpException):
$status = 405;
$title = "Method not allowed exception";
$detail = "The HTTP method '{$request->getMethod()}' is not allowed here";
break;
case ($e instanceof UnprocessableEntityHttpException):
$status = 422;
$title = "Unprocessable Entity";
$detail = "We're sorry, we can not process your data what you've just sent to us";
break;
}
return response()->json([
'errors' => [
[
'status' => $status,
'source' => ['pointer' => $request->getUri()],
'title' => $title,
'detail' => get_class($e)
]
]
], $status);
return parent::render($request, $e);
}
The NotFoundHttpException returns proper error as expected:
{
"errors": [
{
"status": 405,
"source": {
"pointer": "http:\/\/localhost:8001\/api\/v1\/df\/documents"
},
"title": "Method not allowed exception",
"detail": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException"
}
]
}
The problem is I can not catch validation errors like UnprocessableEntityHttpException, I get this back:
{
"data.type": [
"The data.type field is required."
]
}
How can I handle/transform all my exceptions to a proper JSON response?