【问题标题】:@ExceptionHandler for Wrapped Exception / getCause() in Spring@ExceptionHandler 用于 Spring 中的包装异常 / getCause()
【发布时间】:2018-11-04 23:22:22
【问题描述】:

有谁知道使用@ExceptionHandler 包装异常的最佳/最简单方法?

我有一个自定义 org.springframework.core.convert.converter.Converter 用于转换 @PathVariable,如果输入超出标准范围,它会引发自定义运行时异常。

这最终被 Spring 包裹在 ConversionException 中,我可以在 Controller Advice 中使用 @ExceptionHandler(ConversionException.class) 处理。

但是我必须.getCause() 并使用instanceof 来确定底层异常是否是我感兴趣的类型。此时我可以使用对.sendError() 的响应,但如果我有不同的潜在异常我不知道该怎么办?

如果我重新抛出原始异常,我会收到一条令人讨厌的日志消息“无法调用 @ExceptionHandler 方法”,而且感觉不对。

有没有一种简单的方法来做类似@ExceptionHandler(MyCustomConversionException.class) 的事情,其中​​MyCustomConversionException@ControllerAdviceConversionException 的原因?

谢谢!

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    创建一个 ControllerAdvice 类 @ControllerAdvice,它允许您创建多个 @ExceptionHandler 条目。每个方法都可以引用单个异常或多个异常。

    例如:

    @ControllerAdvice
    public class ExceptionController extends ResponseExceptionHanlder {
      @ExceptionHandler(value = { NumberFormatException.class })
      protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
         //TODO: Handle exception
         return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
      }
    
      @ExceptionHandler(value = { InvalidClassException.class })
      protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
         //TODO: Handle exception
         return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
      }
    
      @ExceptionHandler(value = { MaxUploadSizeExceededException.class,  SizeLimitExceededException.class })
      protected ResponseEntity<Object> handleNumberFormatExcpetion(Exception ex, WebRequest request) {
         //TODO: Handle exception
         return handleExceptionInternal(ex, 'error', new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
      }
    
    }
    

    【讨论】:

    • 感谢您的回答,但这只是设置标准@ControllerAdvice 类的方法,我要问的是如何处理在其他异常中包装的异常.
    • 其实,对不起,我看到你在做什么,我认为基类应该是ResponseEntityExceptionHandler,我会研究一下谢谢!
    • 目前还不清楚这个答案在做什么以及它如何回答这个问题。它甚至没有编译。
    • 它的作用很清楚。它处理多个抛出的异常。它无法编译,因为它是一个 sn-p,它取决于 OP 根据他们的需要来实现它。
    • 这个答案是错误的——它没有捕获 Wrapped Exceptions,我只是试了一下,没有找到我的处理程序。
    猜你喜欢
    • 2017-03-29
    • 2011-05-12
    • 1970-01-01
    • 2015-12-17
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多