When and where to handle exceptions with Laravel in developing an API

Asked

Viewed 483 times

4

I’m having some doubts when it comes to handling errors in an API.

  • We should always treat an Exception?
  • It would be correct to return a message like the one below?

Return:

{
  "success" : false,
  "error" : {
    "message" : "<msg da exception>",
    "codeStatus" : "codStatus da exception"
  }
}
  • Or if I should capture all Exceptions and launch a custom message?

1 answer

0

When I create an API, I always treat the exceptions that my application throws because its format is usually released in HTML, and since it is an API, I want it to be released in JSON format.

I create my custom exceptions in format:

{
   "messages": "algum erro"
}

I don’t usually put Success stating that it went wrong or right because the HTTP Status Code itself already informs this, but in general, the format you mentioned is also good, goes to the taste.

Standard Laravel exceptions are usually released in HTML format even if Header Accept is [application/json]. To solve this problem, I went to App Exceptions Handler.php and added the following code in the "render render":

if($request->expectsJson())
        return $this->seuMetodoParaTratarExcecoes($request, $exception);

Within this method, then you put some check to turn the exception that would be launched into HTML to a json. If you want an example:

 if($exception instanceof NotFoundHttpException)
        return response()->json([
            'messages' => 'Recurso não encontrado'
        ], Response::HTTP_NOT_FOUND);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.