How to use HttpStatus messages?
For example, I have this controller and what I do is send HttpStatus.OK
, that is for success, but what if it fails, what should I do?
@PostMapping("/createMeet")
public ResponseEntity<Meet> createMeet(@RequestParam("user") Long idUser,@RequestBody Meet meet ) {
return new ResponseEntity<Meet>(meetService.createMeet(idUser, meet), HttpStatus.OK);
}
Spring provides a mechanism for managing exceptions through the tag
@ControllerAdvice
that can be used in a class to use it as an http interceptor, so that each exception that you define goes to this class and you can modify the response that you decide to send in exception case as well as the "HTTP status code" . We are going to see the whole process, the first thing is to have a controller with our endpoint:This class is the controller, to simplify the code we have not added the service injection that defines the getCoffee method that corresponds to the URI:
One important thing is that the controller does not have any type of logic since this is not its function, its function is to redirect the HTTP requests received by the server to the corresponding service that is in charge of carrying out the necessary logic, including exception management. Following our example:
For simplicity, we've removed the data access logic from the service but keep in mind the separation of responsibilities (calling a repository to fetch the data). Now, going back to the original question, I need to be able to send responses in case of errors since my current code will only send a 200OK or 500INTERNAL_SERVER_ERROR by default in case of failure of my code. For this, Spring makes the @ControllerAdvicer tag available to you and there are several things you can do with it, let's see a very simple example, we create our exception handler:
This exception handler is called in each HTTP request when an exception is thrown and searches if there is a method that is activated with that exception (the one defined in
@ExceptionHandler
), in our example, we have put Exception that basically corresponds to any error in our application , this can be useful if we want to modify the general error response for any exception, we can modify the error message, status code, define a different error json than the generic one... This layer is in charge of handling exceptions in controllers and nothing more.But in our case, we may want to add a new exception that corresponds to a different http code, for example, in our case we can request a coffee with an id that does not exist in the database and return an error response with a code 404NOT_FOUND . For this we have to throw a specific exception in our service (ALWAYS in a service that is in charge of the logic of our application). In our case, being a "not found", we can create an Exception EntityNotFoundException():
Well, now that we have our custom exception (an exception that can be thrown when there is no coffee in the database), we have to map this exception to an HTTP 404 response, for this we add the corresponding method to the exception handler that we have previously created:
Now our http requests have two possible error responses, the generic 500 that we have previously defined or the 404 that we have defined in the second method. In order for our server to send this 404, we simply have to throw the EntityNotFoundException in our service when we consider it necessary, for example:
And with this there would be our complete flow, fully respecting the separation of responsibilities. Note that when throwing the exception you can send a message as a parameter that is what is being added to the log in the exception handler, you can use this to send information to the exception handler that you may need to manage the error.
In the case of having to respond to other statuses (400, 404, 500, etc) you would have to handle exceptions in the controller, remember that status 200 is when everything goes as expected.
But where do those errors come from? well, they will be defined in the BO (@Service) of your application by yourself, according to the logic proposed for the development of your application.
Here an example:
Service
You can see how in case of not finding any contact in the database I will return a specific exception (made by me for my particular case) which will be cached in the controller and treated with a 404 NOT FOUND status.
Controller