ExceptionHandler由多个控制器共享

Jih*_*ine 5 java spring spring-mvc

是否可以在类中声明ExceptionHandlers并在多个控制器中使用它们,因为在每个控制器中复制粘贴异常处理程序将是多余的.

- 声明异常处理程序:

@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
}
Run Code Online (Sandbox Code Playgroud)

-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 {...}
Run Code Online (Sandbox Code Playgroud)

-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 {...}
Run Code Online (Sandbox Code Playgroud)

cde*_*zaq 5

一种方法是使用控制器扩展的基类(可以是抽象的).然后,基类可以保存所有"常见"事物,包括异常处理程序,以及加载常见模型数据,例如用户数据.