zoukankan      html  css  js  c++  java
  • 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

    声明:本博客文章为原创,只代表本人在工作学习中某一时间内总结的观点或结论。转载时请在文章页面明显位置给出原文链接。
  • 相关阅读:
    fastapi+vue搭建免费代理IP网站部署至heroku
    如何选择免费代理ip,需要注意哪些指标值和基本参数
    如何部署MongoDB并开启远程访问Docker版
    Linux设置Frps Frpc服务开启启动
    Docker搭建VS Code Server ,设置访问密码随时随地写代码
    薅羊毛须及时 多平台微信线报提醒脚本
    python+selenium实现百度关键词搜索自动化操作
    用python selenium 单窗口单IP刷网站流量脚本
    杂记 内容会在留言中补充
    c#杂记
  • 原文地址:https://www.cnblogs.com/se7end/p/14776128.html
Copyright © 2011-2022 走看看