Anyone know what is the best way to handle errors in Laravel, there is any rules or something to follow ?
Currently i'm doing this :
public function store(Request $request)
{
$plate = Plate::create($request->all());
if ($plate) {
return $this->response($this->plateTransformer->transform($plate));
} else {
// Error handling ?
// Error 400 bad request
$this->setStatusCode(400);
return $this->responseWithError("Store failed.");
}
}
And the setStatusCode and responseWithError come from the father of my controller :
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
public function responseWithError ($message )
{
return $this->response([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
]);
}
But is this a good way to handle the API errors, i see some different way to handle errors on the web, what is the best ?
Thanks.
Try this, i have used it in my project (app/Exceptions/Handler.php)
Now Handle Api exception
After that custom Api handler response
Always add
Accept: application/json
in your api or json request.Good way to handle the Api errors is to handle this errors in app\Exceptions\Hendler.php in render method.
In my opinion I'd keep it simple.
Return a response with the HTTP error code and a custom message.
Or if you want to throw a caught error you could do :
You can even use this for sending successful responses:
This way no matter which service consumes your API it can expect to receive the same responses for the same requests.
You can also see how flexible you can make it by passing in the HTTP status code.
Laravel is already able to manage json responses by default.
Withouth customizing the render method in app\Handler.php you can simply throw a Symfony\Component\HttpKernel\Exception\HttpException, the default handler will recognize if the request header contains Accept: application/json and will print a json error message accordingly.
If debug mode is enabled it will output the stacktrace in json format too.
Here is a quick example:
Here is laravel response with debug off
And here is the response with debug on
Using HttpException the call will return the http status code of your choice (in this case internal server error 500)