• SpringMVC对异常请求增加处理


    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到第一位。

    作者:Se7end

    声明:本博客文章为原创,只代表本人在工作学习中某一时间内总结的观点或结论。转载时请在文章页面明显位置给出原文链接。
  • 相关阅读:
    解决shiro多次从redis读取session的问题
    软件测试其他方法
    异常HTTP Status 500
    支付
    java面试
    SQL入门
    软件测试理论基础
    软件测试学习第一章
    Linux在终端命令行模式下智能补全功能以及组合键
    Linux安装
  • 原文地址:https://www.cnblogs.com/se7end/p/14776128.html
Copyright © 2020-2023  润新知