【问题标题】:Spring Boot 2.1 : Exception thrown in WebMvcConfigurer#addFormatters(...) not catched in @RestControllerAdviceSpring Boot 2.1:WebMvcConfigurer#addFormatters(...) 中引发的异常未在 @RestControllerAdvice 中捕获
【发布时间】:2019-06-02 11:35:00
【问题描述】:

从 Spring Boot 2.0 更新到 2.1 后,WebMvcConfigurer#addFormatters( FormatterRegistry registry ) 中抛出的所有异常都不再在 @RestControllerAdvice 中捕获。我将此方法用于附加转换器。

例如:

public class ConvertersContainer {

    public static class StringToStatusConverter implements Converter<String, Status> {

       @Override
       public Status convert( String source ) {
           return Status.findStatus( source );
       }
    }
}

Status 是一个枚举。

public enum Status {

   HAPPY("happy"), ANGRY("angry");

   private String title;

   public static Status findStatus( final String title) {
    return stream( values() )
            .filter( status-> status.getTitle().equals( title) )
            .findFirst()
            .orElseThrow( () -> new StatusNotFoundException( "...." ) );
   }
}

还有StatusNotFoundException extends RuntimeException {}

我这样注册了这个转换器:

@Configuration
public class ConverterRegister implements WebMvcConfigurer {

     @Override
    public void addFormatters( FormatterRegistry registry ) {
       registry.addConverter( new ConvertersContainer.StringToStatusConverter() );
       WebMvcConfigurer.super.addFormatters( registry );
    }
}

和控制器建议:

@RestControllerAdvice
public class Advice {

   @ExceptionHandler( StatusNotFoundException .class)
   protected String handleStatusNotFoundException(StatusNotFoundException ex) { ...   }
}

当我断点时,方法Status#findStatus(...) 执行得很好,但在@RestControllerAdvice 中从未捕获到异常。我究竟做错了什么? 非常感谢

【问题讨论】:

  • 您是否尝试捕获该异常并记录它是否被抛出?
  • @JonathanJohx 是的,我能抓住它
  • 你的处理方法应该是public吗?

标签: spring spring-boot spring-mvc exception exception-handling


【解决方案1】:

似乎 Spring 包装了转换过程中抛出的所有异常,并抛出 org.springframework.beans.TypeMismatchException 而不是用户的自定义异常。

在我看来这种行为是不正常的,如果在转换过程中抛出异常,这个异常应该优先于所有框架的异常。所以要解决这个问题,我们必须extends ResponseEntityExceptionHandler 并覆盖它的protected ResponseEntity&lt;Object&gt; handleTypeMismatch(...)

谢谢@Eric(那个人评论了上面的问题)。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2012-06-05
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多