Being Each ExceptionHandler is limited to controller. In the case of where multiple controllers exists, @ExceptionHandler using will not be affective and increase duplicate code.
To get Global Exception Handling
Application -wide across all controllers and all exceptions
- While handling it is good to create package-level handlers
- Control the controllers by their annotations (global handling specific to some controllers by include/exclude)
@ControllerAdvice : comes from Aspect Programming
This is single advice across application wide
can also create domain level (scope level)
While writing:
- Mark with @ControllerAdvice
- Add one or many @ExceptionHandler for specific/group of exceptions like @ExceptionHandler
- Can also add catch all exception handler (Refer @Exceptionhandler post)
like below
Spring Provides @ControllerAdvice
and
@RestControllerAdvice (This is @ControllerAdvice + @ResponseBody) - for REST Services
Topic 6:
Scoping the ControllerAdvice for particular packages also can be done so that this global handler is applicable for only the packages.
to assign to only set of controllers not to packages then
PLEASE NOTE THAT , WE SHOULD NOT HAVE MULTIPLE @CONTROLLERADVICES IN ONE APPLICATION. TO MAKE IT THERE SHOULD BE MORE CARE NEED TO BE TAKEN CARE LIKE USING PRIORITY, ETC., GENERALLY IT IS NOT RECOMMENDED AS IT IS NOT PREDICTABLE
Topic 7:
When multiple ControllerAdvices are present , it will be picked up in Alphabetical order (Please check in your system). As this is not predictable, "Order" annotation can be used to set the order. Generally takes integer value
No comments:
Post a Comment