gpt4 book ai didi

java - @ControllerAdvice 方法似乎绕过了拦截器

转载 作者:行者123 更新时间:2023-11-30 08:27:54 30 4
gpt4 key购买 nike

我有一个用 @ControllerAdvice 注释的类,为我的 api 提供了一些中央异常处理。它处理的异常之一是 MethodArgumentNotValidException,当用 @Valid 注释的请求方法参数验证失败时抛出该异常。

在我的应用程序中,我还有一个 CORS 拦截器设置,它在请求成功时将“Access-Control-Allow-Origin” header 添加到 servlet 响应。但是,似乎当对用 @Valid 注释的参数验证失败时,我的拦截器被绕过了。我的异常处理程序需要发回无效表单字段的错误信息,以便它们可以在浏览器中处理。

只是想知道当抛出异常时我的拦截器被绕过是否是正常行为,或者我是否缺少 @ControllerAdvice 类中的某些配置。

最佳答案

这确实是正常行为。

来自 HandlerInterceptor.postHandle 的 javadoc

Intercept the execution of a handler. Called after HandlerAdapter actually invoked the handler, but before the DispatcherServlet renders the view. Can expose additional model objects to the view via the given ModelAndView. DispatcherServlet processes a handler in an execution chain, consisting of any number of interceptors, with the handler itself at the end. With this method, each interceptor can post-process an execution, getting applied in inverse order of the execution chain.

可以说 MethodArgumentNotValidException 在实际调用方法之前抛出,它是在准备实际方法调用时调用的。实际上,postHandle 仅在成功执行/调用该方法后才执行。如果出现异常,仅调用 preHandleafterCompletion 方法。

关于java - @ControllerAdvice 方法似乎绕过了拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551888/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com