SpringMVC异常处理

😂 这篇文章最后更新于1737天前,您需要注意相关的内容是否还可用。
目录导航
  • 异常处理
    • 编写异常类
    • 自定义异常处理器
    • 配置异常处理器
    • 异常处理在控制层使用
  • 异常处理

    系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理。

    编写异常类

    public class CustomException extends Exception {
        private String message;
        public CustomException(String message) {
            this.message = message;
        }
        public String getMessage() {
            return message;
        }
    }

    自定义异常处理器

    设置如果是指定错误跳转到指定错误页面,并返回相应错误信息

    public class CustomExceptionResolver implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest request,
                                             HttpServletResponse response, Object handler, Exception ex) {
            ex.printStackTrace();
            CustomException customException = null;
    //如果抛出的是系统自定义异常则直接转换
            if (ex instanceof CustomException) {
                customException = (CustomException) ex;
            } else {
    //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。
                customException = new CustomException("系统错误,请与系统管理 员联系!");
            }
            ModelAndView modelAndView = new ModelAndView();
            //存入错误信息
            modelAndView.addObject("message", customException.getMessage());
            //跳转错误页面
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }

    配置异常处理器

    <!-- 配置异常处理器 -->
    <bean id="sysExceptionResolver" class="com.cheng.exception.CustomExceptionResolver"/>

    异常处理在控制层使用

    在控制层的try...catch中throw new CustomException("系统错误")即可