首页 > 解决方案 > 如何处理所有标准 Spring MVC 异常

问题描述

我已经实现了我的异常处理程序,我在其中捕获了我的自定义异常。现在,我只是想知道是否有一种很好的方法来捕获类中定义的所有异常: org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

按照handleException方法的定义:

/**
 * Provides handling for standard Spring MVC exceptions.
 * @param ex the target exception
 * @param request the current request
 */
@ExceptionHandler({
    HttpRequestMethodNotSupportedException.class,
    HttpMediaTypeNotSupportedException.class,
    HttpMediaTypeNotAcceptableException.class,
    MissingPathVariableException.class,
    MissingServletRequestParameterException.class,
    ServletRequestBindingException.class,
    ConversionNotSupportedException.class,
    TypeMismatchException.class,
    HttpMessageNotReadableException.class,
    HttpMessageNotWritableException.class,
    MethodArgumentNotValidException.class,
    MissingServletRequestPartException.class,
    BindException.class,
    NoHandlerFoundException.class,
    AsyncRequestTimeoutException.class
})
@Nullable
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) throws Exception {
...
}

所以基本上我希望我ExceptionHandler能够捕获上面列出的所有异常。最好避免覆盖每一个句柄方法。我需要这个才能将带有状态、errorMessage、时间戳、ecc 的经典 json 发送回客户端。

标签: springspring-bootspring-mvc

解决方案


推荐阅读