SpringMVC的一个请求问题。
如果请求成功,走Filter,Interceptor都没有问题。
如果请求失败,比如说请求里面验证不通过,然后抛出了一个异常。
这个Filter和Interceptor都不能处理到这个异常(Aspect可以处理,但是又不想用这个。@ControllerAdvice也可以)。
最后看了一下DispatcherServlet里面的请求,发现了一个处理异常的类,HandlerExceptionResolver的接口。
在里面可以处理自己的异常,也可以返回自己的视图。
返回null的时候会执行下一个视图,返回有值停止循环。
public interface HandlerExceptionResolver { /** * Try to resolve the given exception that got thrown during handler execution, * returning a {@link ModelAndView} that represents a specific error page if appropriate. * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty} * to indicate that the exception has been resolved successfully but that no view * should be rendered, for instance by setting a status code. * @param request current HTTP request * @param response current HTTP response * @param handler the executed handler, or {@code null} if none chosen at the * time of the exception (for example, if multipart resolution failed) * @param ex the exception that got thrown during handler execution * @return a corresponding {@code ModelAndView} to forward to, * or {@code null} for default processing in the resolution chain */ @Nullable ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex); }
通过实现 WebMvcConfigurer 接口来注册这个异常处理器
/** * Extending or modify the list of exception resolvers configured by default. * This can be useful for inserting a custom exception resolver without * interfering with default ones. * @param resolvers the list of configured resolvers to extend * @since 4.3 * @see WebMvcConfigurationSupport#addDefaultHandlerExceptionResolvers(List, org.springframework.web.accept.ContentNegotiationManager) */ default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { }
这里需要注意,如果自己异常过滤器不处理返回信息,只需要处理异常信息。需要在自己的实现里面返回null,并且在这里注册的时候,将自己的注册器add到第一位。