Answer the question
In order to leave comments, you need to log in
How to properly return errors in your API, Laravel?
Greetings. I return errors in my API in this format:
{
"error" : {
"error_code" : 1,
"error_details" : { ... }
}
}
{
"count" => "The count field must be an integer."
}
Answer the question
In order to leave comments, you need to log in
I can manually return every method in my API, but it doesn't look right
Response::macro('api', function ($code, $data) {
return new ApiResponse($code, $data);
});
As the main API error indicator, I use HTTP statuses. Laravel supports many cases out of the box:
Thus, manually returning errors will also have to be returned, but in most cases Laravel will do this for you.
There is no single error response format from the http api. There are some contenders, but this is it. It is not necessary to return, it is necessary to throw exceptions and process them in the handler. Better - if there is some one base class AppException, with which you can control the compliance of your own custom errors for the presence of the necessary fields (code, http code, message, meta info). How I do it (so far it’s rolling):
1) from the server I give to each unique error (for example, the one that goes beyond the scope of the validator) my error code, as with error_code. Trivial errors (such as not found or validation) do not have them, since the http code points to it (such as 404 and 422).
2) I also write a message for each exception in the code, which I also give in response during development. On production, I cut down the debug and the message disappears from the response from the server, the http code and "own code" remain.
If we talk only about validation error, then I do it like with error_details, and then the fronter deals with it the way it fits into the design.
I always return a universal mechanism through throw exception for my errors, and suddenly where I miss an exception, it will be processed by the frontend accordingly.
Also, for validation, there are exceptions that will go with your errors in the same format (do not process twice) and axios callbacks work, etc. Http code can be controlled in exception
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question