@taijuten I've the same setup as you do: My ApiController is extended by my other Controllers and it sometimes throws Exceptions.
But when I capture these Exceptions (through the Exception Handler), I still want these to be rendered as a json object (like any other response rendered by my APIController). That means that either I handle my Exceptions like this :
// class App\Exceptions\Handler
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->json([
'data' => [
'message' => 'Resource not found',
'status_code' => Response::HTTP_NOT_FOUND
]
], Response::HTTP_NOT_FOUND);
} elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return response()->json([
'data' => [
'message' => 'Endpoint not found',
'status_code' => Response::HTTP_NOT_FOUND
]
], Response::HTTP_NOT_FOUND);
}
return response()->json([
'data' => [
'message' => $e->getMessage(),
'status_code' => Response::HTTP_BAD_REQUEST
]
], Response::HTTP_BAD_REQUEST);
}
which is painful to read and maintain..
I'm currently going with a custom ResponseTrait that I use in my ApiController and in my Exception/Handler classes.
That allows me to update my code to this :
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return $this->setStatusCode(Response::HTTP_NOT_FOUND)->respondWithError('Resource not found');
} elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return $this->setStatusCode(Response::HTTP_NOT_FOUND)->respondWithError('Endpoint not found');
}
return $this->setStatusCode(Response::HTTP_BAD_REQUEST)->respondWithError($e->getMessage());
}
```