系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、通过测试手段减少运行时异常的发生。

       系统的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 httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        CustomException customException=null;
        //如果抛出的是系统自定义异常则直接转换
        if(e instanceof CustomException){
            customException=(CustomException)e;
        }else{
            customException=new CustomException("系统错误,请与管理员联系");
        }
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("message",customException.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

三)配置异常处理器

<bean id="exceptionResolver" class="com.company.exception.CustomExceptionResolver"></bean>

四)异常页面和访问页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
执行失败。
<h1>${message}</h1>
</body>
</html>
<fieldset>
    <h1>自定义异常处理</h1>
    <a href="${pageContext.request.contextPath}/testException">测试异常</a>
</fieldset>

五)控制器方法处理

    @RequestMapping("/testException")
    public String testException(Model model,@RequestParam(value = "name",required = false) String name) throws Exception{
        CustomException customException=new CustomException("用户名不能为空,请重新填写");
        if(StringUtils.isEmpty(name)) {
            throw customException;
        }
        model.addAttribute("message","没有异常");
        return "success";
    }

效果:

 

 posted on 2019-11-29 20:20  会飞的金鱼  阅读(131)  评论(0)    收藏  举报