重构类似的Spring MVC ExceptionHandlers

时间:2014-05-06 03:30:59

标签: spring-mvc spring-java-config

我在几个Spring MVC控制器中有以下异常处理程序重复。我知道那些可以重构为单个bean 或者WebMvcConfigurerAdapter,但是我找不到任何例子。我没有任何观点,它是一个REST API ...

如何使用java配置重构那些?如果可能的话,我更愿意将它们重构为自定义WebMvcConfigurerAdapter

......
......
@ExceptionHandler({MissingServletRequestParameterException.class,
    UnsatisfiedServletRequestParameterException.class,
    HttpRequestMethodNotSupportedException.class,
    ServletRequestBindingException.class,
    TypeMismatchException.class
})
public ResponseEntity<DataCarrier> handleException(Exception exception) {
    logger.warn("A bad input received.");
    return new ResponseEntity<DataCarrier>(new ErrorDto("Input data is not valid."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({AccountNotFoundException.class, NoAccountException.class})
public ResponseEntity<DataCarrier> noAccountFoundException(Exception exception) {
    return new ResponseEntity<DataCarrier>(HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler({HeaderPropertyException.class})
public ResponseEntity<DataCarrier> headerPropertyException(Exception exception) {
    logger.error("[{}].", exception.getMessage(), exception);
    return new ResponseEntity<DataCarrier>(HttpStatus.INTERNAL_SERVER_ERROR);
}

0 个答案:

没有答案