springMVC入门(五)------统一异常处理

简介

系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过异常捕获获取异常信息,后者需通过规范代码、提高代码路绑定减少运行时异常的发生
异常处理思路:无论dao层、service层、controller层的异常均向上层抛出,最后由springMVC前端控制器捕获交由统一异常处理器处理(一个系统只有一个异常处理器),对于自定义的异常(预期的异常),可根据实际需求处理,对于运行时异常,可显示为“未知错误”

实现方式

1、继承HandlerExceptionResolver

public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
 
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String message = "unknown exception";
        //判断是否自定义异常
        if(ex instanceof CustomException) {
            CustomException customException = (CustomException) ex;
            message = customException.getMessage();
        }
        return new ModelAndView("/WEB-INF/jsp/error.jsp").addObject("message", message);
    }
 
}

2、配置springmvc配置文件
配置自定义的异常处理器bean即可

<!-- 配置全局异常处理器 -->
<bean class="com.springmvc.exception.GlobalHandlerExceptionResolver"></bean>

3、异常处理页面

<html>
<body>
<h2>Hello World!</h2>
${message}
</body>
</html>

4、测试代码
自定义异常:

public class CustomException extends Exception {
 
    public CustomException(String message) {
        super(message);
    }
}

模拟controller层抛出异常

@RequestMapping("/addUser")
 public ModelAndView addUser(User user) throws Exception {
       if(null == user) {
           throw new CustomException("user can not be null");
       }
       return new ModelAndView("/index.jsp");
 }

结果:

posted @ 2018-08-30 14:26  nlskyfree  阅读(187)  评论(0编辑  收藏  举报