Spring @RestControllerAdvice When and Why?
@RestControllerAdvice
annotation is the composition of two annotations: 1- @ControllerAdvice
and 2- @ResponseBody
. In this article we will talk about this annotation and the necessity of using it.
1- Understanding @ExceptionHandler
By using this annotation in a rest controller you can handle exceptions which is thrown in the same controller methods which are annotated by @GetMapping, @PostMapping, ...
or @RequestMapping.
In this way they are some options for handling such exceptions like redirecting to an error page or returning custom error messages.
Or
2- Applying Exception Handler To Whole Project
As mentioned above @ExceptionHandler
just worked in the same controller and if you have more than one controller you should apply above code (if you want to use@ExceptionHandler
) to all controller.
But there is a better way, using :
@RestControllerAdvice
or @ControllerAdvice
By using @RestControllerAdvice
also you will have the features of @ResponseBody.
Usage: