简体   繁体   English

如果端点路径未知,ExceptionHandler 不会捕获 HandlerInterceptor 异常

[英]ExceptionHandler doesn't catch HandlerInterceptor exception if endpoint path is unknown

I have a component that implements the HandlerInterceptor interface, and implements the preHandle method.我有一个实现 HandlerInterceptor 接口并实现 preHandle 方法的组件。 In this method I retrieve a parameter from the request, and throw an IllegalArgumentException if that parameter is missing.在此方法中,我从请求中检索一个参数,如果缺少该参数,则抛出 IllegalArgumentException。

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String parameter = request.getHeader("parameter123");
        if (StringUtils.isEmpty(parameter)) {
            throw new IllegalArgumentException("parameter123 not specified");
        }
        [...]
        return true;
    }

In another class annotated with @ControllerAdvice, I have a ExceptionHandler that catches the IllegalArgumentExceptions and turns those into a formatted response with HTTP status code 400.在另一个用@ControllerAdvice 注释的 class 中,我有一个 ExceptionHandler,它捕获 IllegalArgumentExceptions 并将其转换为状态代码为 HTTP 的格式化响应 400。

When this is executed by triggering a valid path of my API, everything works just fine.当通过触发我的 API 的有效路径执行此操作时,一切正常。 Problems arise when I try to call an invalid/unexisting path of my API. The HandlerInterceptor is called and the exception is thrown but my ExceptionHandler is not triggered and the result is a basic HTTP status code 500 exception.当我尝试调用 API 的无效/不存在路径时出现问题。调用 HandlerInterceptor 并抛出异常但未触发我的 ExceptionHandler,结果是基本的 HTTP 状态代码 500 异常。 It seems to both override the basic HTTP status 404 mechanism, while also preventing the triggering of my ExceptionHandlers (even an ExceptionHandler on Exception.class doesn't ever get called).它似乎既覆盖了基本的 HTTP 状态 404 机制,同时也阻止了我的 ExceptionHandlers 的触发(即使是 Exception.class 上的 ExceptionHandler 也不会被调用)。

Any explanations regarding this behaviour are welcome !欢迎对此行为进行任何解释! Thanks谢谢

Although this may be an old question, I want to provide an answer for anyone who may come across it in the future.虽然这可能是一个老问题,但我想为将来可能遇到它的任何人提供一个答案。

When you raise an exception in the preHandle method of a HandlerInterceptor, it may be wrapped in another exception called NestedServletException.当您在 HandlerInterceptor 的 preHandle 方法中引发异常时,它可能被包装在另一个称为 NestedServletException 的异常中。 This is a specific exception thrown by the Spring framework.这是 Spring 框架抛出的特定异常。

It's worth noting that NestedServletException is a runtime exception that occurs when a servlet or filter throws an exception.值得注意的是,NestedServletException 是在 servlet 或过滤器抛出异常时发生的运行时异常。 It encloses the original exception and provides additional information about the location where the exception occurred.它包含原始异常并提供有关异常发生位置的附加信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM