As in all application development, proper error handling must be in place to complete the system. In this case, we will present an entity not found exception during a get operation.
[open CategoryController class, oneCode method] – Code available below
In this case, we are throwing a CategoryNotFoundException if findByCode returns null. A CategoryNotFoundException extends an AbstractResourceNotFoundException with a constructor that formats the error message. This will serve as the parent class that can be extended to other entities.
Now, let’s go to the error handler. We can implement several ways, but for this exercise, we will use 2.
The first one is by using @RestControllerAdvice annotation.
[open CategoryNotFoundAdvice class] – Code available below
Here we have a method that accepts an exception and an @ExceptionHandler annotation that specifies the exception that it handles. We can also specify the response status via @ResponseStatus annotation. Or if you want you can return a ResponseEntity, and in that case, you can remove the @ResponseStatus annotation.
[open ApplicationExceptionResponseHandler class] – Code available below
The second approach is by extending the class ResponseEntityExceptionHandler, it lets you customize the Spring exception message. A well-known instance is when handling the validation errors as can be seen from the handleMethodArgumentNotValid method.
Run create tests without code to see the formatted errors.
And that’s all for this lecture. I hope you have learned about error handling and how you can incorporate it into your application.
In the next video, we will discuss how you can version your API.