Spring MVC|异常处理

异常处理的思路

  系统中异常包括两类,预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等方法减少运行时异常的发生。
  系统的dao、service、controller出现异常后全部 throws Exception 向上抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理,如下图:
1.PNG

实现步骤

  1. 自定义一个异常类和错误界面。
  2. 自定义异常处理器(实现HandlerExceptionResolver接口)。
  3. 把自定义的异常处理器加入到 IOC 容器中(使用@Component注解或者xml配置)。

实现示例

自定义一个异常类

/**
 * 自定义异常类
 */
public class CustomException extends Exception{
    private String message;

    public CustomException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

友好的错误界面(交给前端人员)

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>错误界面</title>
</head>
<body>
    ${error_msg}
</body>
</html>

自定义异常处理器并加入到 IOC 容器中

/**
 * 自定义异常处理器
 */
@Component
public class MvcResolverExceptionResolver implements HandlerExceptionResolver {
    /**
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o 当前对象
     * @param e 捕获到的异常
     * @return ModelAndView
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        MvcResolveException mvcResolveException = null;
        //如果该异常为自定义异常,则直接强转
        if (e instanceof MvcResolveException) {
            mvcResolveException = (MvcResolveException) e;
        } else {
        //不是,则直接创建一个系统异常对象
            mvcResolveException = new MvcResolveException("服务器出小差了,请稍后...");
        }
        ModelAndView modelAndView = new ModelAndView();
        //把错误信息加入到request域中
        modelAndView.addObject("error_msg", mvcResolveException.getMessage());
        modelAndView.setViewName("error");//跳转到错误界面
        return modelAndView;
    }
}

异常处理演示

  在 controller 方法中手动制造一个异常。

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/exceptionResolver")
    public String testExceptionResolver() throws CustomException {
        try {
            int i = 2 / 0;
        } catch (Exception e) {
            throw new CustomException("发生CustomException异常了");
        }
        return "success";
    }
}

  请求这个方法。

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
    <a href="user/exceptionResolver">点击测试</a>
</body>
</html>
发布了46 篇原创文章 · 获赞 1 · 访问量 2505
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章