ExceptionHandler由多个控制器共享

时间:2011-09-26 15:03:02

标签: java spring spring-mvc

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

-Class声明异常处理程序:

@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 个答案:

答案 0 :(得分:5)

这样做的一种方法是拥有一个控制器扩展的基类(可以是抽象的)。然后,基类可以保存所有“常见”的东西,包括异常处理程序,以及加载常见的模型数据,例如用户数据。

答案 1 :(得分:1)

您可以将HandlerExceptionResolver声明为将在每个控制器上使用的bean。您只需检查类型并按照您的意愿处理它。

答案 2 :(得分:0)

或者您可以创建一个异常处理接口并将其注入控制器类。

答案 3 :(得分:0)

或者您可以使用带有@ControllerAdvice批注的类。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IdentifiersNotMatchingException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public 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)
    @ResponseBody
    public String handleResourceNotFoundException(ResourceNotFoundException e) {
        logger.error("Resource Not Found Error", e)
        return "Resource Not Found Error: " + e.message
    }
}