Learn How to Handle Exception in Spring Rest Api
Go Back to Course Outline Repositories https://github.com/terawarehouse/terawarehouse-catalog https://github.com/terawarehouse/tera...
https://www.czetsuyatech.com/2019/08/spring-rest-exception-handling.html
Repositories
- https://github.com/terawarehouse/terawarehouse-catalog
- https://github.com/terawarehouse/terawarehouse-react
[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.
[open postman]
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.
Post a Comment