ExceptionHandler shared by multiple controllers

Is it possible to declare ExceptionHandlers in a class and use them in several controllers, because copying exception handlers in each controller will be redundant.

-Class declares exception handlers:

@ExceptionHandler(IdentifiersNotMatchingException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) def @ResponseBody String handleIdentifiersNotMatchingException(IdentifiersNotMatchingException e) { logger.error("Identifiers Not Matching Error", e) return "Identifiers Not Matching Error: " + e.message } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) def @ResponseBody String handleResourceNotFoundException(ResourceNotFoundException e) { logger.error("Resource Not Found Error", e) return "Resource Not Found Error: " + e.message } 

-ContactController

 @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(value = "contact/{publicId}", method = RequestMethod.DELETE) def @ResponseBody void deleteContact(@PathVariable("publicId") String publicId) throws ResourceNotFoundException, IdentifiersNotMatchingException {...} 

-LendingController

 @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(value = "lending/{publicId}", method = RequestMethod.PUT) def @ResponseBody void updateLending(@PathVariable("publicId") String publicId, InputStream is) throws ResourceNotFoundException {...} 
+4
source share
3 answers

One way to do this is to create a base class that will expand your controllers (can be abstract). Then the base class can store all the โ€œcommonโ€ things, including exception handlers, as well as load general model data, such as user data.

+5
source

You can declare HandlerExceptionResolver as a bean to be used on each controller. You just check the type and process it as you want.

+1
source

Or you can create an interface for handling exceptions and inject it into your controller class.

0
source

All Articles