Spring Boot @ExceptionHandler在开发服务器上工作,但不在本地

时间:2018-11-27 12:28:30

标签: java spring exception-handling

我知道这通常是一个相反的问题,所以在这里我有点措手不及:D

我已经构建了一个用户管理后端,该后端为UI提供了数据。在我们的开发服务器上部署此体系结构时,一切都可以很好地工作。但是,一旦我尝试运行集成测试(我们使用Maven货tomcat进行),或者如果我在本地tomcat中使用war文件,则根本不使用异常处理程序。 Spring只会显示标准的500响应,并将异常转换为正文。

对SO进行类似处理只会导致建议我应该使用@EnableWebMVC,但这不适用于我的后端试图完成的工作,也不会改变任何东西。

我应该如何寻找该问题的解决方案?具体来说,我能以某种方式观察我的controlleradvice是否被扫描,并且有可能为什么不被扫描吗?

编辑:这些是相关文件:

SpringConfiguration:

@Configuration
@ComponentScan(basePackageClasses = {UserManagementSpringConfiguration.class})
@EnableWebSecurity
public class UserManagementSpringConfiguration {

@Configuration
public static class ResourceMappingConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ui/*/usermanagement").setViewName("forward:/usermanagement-ui/index.html");
//            registry.addViewController("/ui/*/*/generator/").setViewName("forward:/generator-ui/index.html");
        registry.addViewController("/ui/*/usermanagement/*").setViewName("forward:/usermanagement-ui/index.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // cache setting, otherwise fonts are not loaded in IE over https
        CacheControl cacheControl = CacheControl.noCache().mustRevalidate();
        registry.addResourceHandler("/ui/**/*").addResourceLocations("/usermanagement-ui/")
                    .setCacheControl(cacheControl);
        }

    }

}

ControllerAdvice:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    public static final Logger LOG = EISLoggerFactory.getLogger(CustomResponseEntityExceptionHandler.class);

    @PostConstruct
    public void postConstruct() {
        LOG.debug("CustomExceptionHandler loaded and ready for use");
    }

    @ExceptionHandler(PasswordMismatchException.class)
    public final ResponseEntity<ErrorDetails> handlePasswordChangeMismatch(
            PasswordMismatchException ex,
            WebRequest request) {
        ErrorDetails errorDetails = new ErrorDetails(
                new Date(),
                ex.getMessage(),
                request.getDescription(false),
                MessageKeys.mismatchedPassword);
        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }
}

1 个答案:

答案 0 :(得分:0)

事实证明,我们编写的模块之一以及项目中包含的模块都为Throwable.class定义了ExceptionHandler。在我的机器上,该ControllerAdvice在我自己的ControllerAdvice之前注册,这使Spring首先在该位置查看。由于Throwable符合要求,因此Spring不再询问其他问题,仅使用该处理程序即可。

解决我当前问题的方法是将@Order(Ordered.HIGHEST_PRECEDENCE)添加到我的ControllerAdvice中。由于我在其中定义的异常非常具体,因此不会引起任何问题。

我还没有找到解释为什么我的机器和我们的开发服务器之间两个ControllerAdvice类的注册顺序如此一致的原因。如果发现任何内容,将会更新。现在,我认为这个问题可以解决。

这个SO问题对于解决这个特定问题至关重要。也许它可以帮助将来的某人将其链接到此处:Setting Precedence of Multiple @ControllerAdvice @ExceptionHandlers

感谢ValentinCarnu为我指出这一点!

相关问题