When and where to handle exceptions with Laravel in the development of an API

2

I have some questions when it comes to handling errors in an API.

  • Should we always handle an exception?
  • Would it be correct to return a message like the one below?

Return:

{
  "success" : false,
  "error" : {
    "message" : "<msg da exception>",
    "codeStatus" : "codStatus da exception"
  }
}
  • Or should I catch all the exception and launch a custom 'message'?
asked by anonymous 13.08.2018 / 16:37

1 answer

0

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

I create my custom exceptions in the format:

{
   "messages": "algum erro"
}

I do not usually add success reporting that it went wrong or right because the HTTP Status Code itself already reports this, but in general, the format you mentioned is also good, goes from the taste.

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

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

Within this method, there you put some verification to transform the exception that would be thrown in HTML to a json. If you'd like an example:

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