SpringMVC_7_异常处理

1.异常处理思路

Controller调用Service,Service调用Dao,异常处理从下层往上层抛,最终有DispatcherServlet找异常处理器进行异常的处理。

2.SpringMVC的异常处理流程图

 

 

 3.SpringMVC的异常处理实现流程:

1)编写自定义异常类(做提示信息)

/**
 * 自定义异常类
 */
public class SysException extends Exception{

    //存储提示信息
    private String message;

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

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

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

 

 

2)编写异常处理器

public class SysExceptionHandler implements HandlerExceptionResolver {
    /**
     * 处理异常的业务逻辑
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //获取异常对象
        SysException sysException = null;
        if(e instanceof SysException){
            e = (SysException)e;
        }else{
            e = new SysException("系统正在维护...");
        }
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //将异常信息写入request域对象
        modelAndView.addObject("errorMsg",e.getMessage());
        //跳转到指定error页面
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

 

 

3)配置异常处理器

 

springmvc.xml:
<!--配置异常处理器-->
    <bean id="sysExceptionHandler" class="com.exception.SysExceptionHandler"></bean>

 

 4)测试

@RequestMapping("/testException")
    public String testException() throws Exception{
        System.out.println("textException执行了....");
        try{
            int a=10/0;
        }catch (Exception e){
            e.printStackTrace();
            throw new SysException("自定义异常");
        }
        return "success";
    }

 

posted @ 2020-09-23 12:33  日进一卒  阅读(126)  评论(0)    收藏  举报