gpt4 book ai didi

java - 多个 Controller 共享的ExceptionHandler

转载 作者:搜寻专家 更新时间:2023-11-01 02:15:16 25 4
gpt4 key购买 nike

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

-声明异常处理程序的类:

@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 {...}

-借贷 Controller

@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 {...}

最佳答案

实现此目的的一种方法是拥有一个您的 Controller 扩展的基类(可以是抽象的)。然后基类可以保存所有“公共(public)”事物,包括异常处理程序,以及加载公共(public)模型数据,例如用户数据。

关于java - 多个 Controller 共享的ExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com