(十一)springMvc 异常处理

版权声明:转载请给出原文链接 https://blog.csdn.net/youngyouth/article/details/82780330


思路

springMvc 中,异常一层一层的往上抛,最后抛给 前端控制器,前端控制器内部会去找 全局异常处理器(一个系统只会有一个),进行统一异常处理 ;

对于运行时异常,捕捉到,就直接提示 未知错误,毕竟谁也不知道运行时会出现什么错误 ;


自定义异常处理类

	/**
	 * 自定义异常类
	 * @author  An
	 * @date 2018年9月20日10:52:24
	 */
	public class CustomerException extends Exception {
	    private String message ;
	    public CustomerException(String message){
	        super(message) ;
	        this.message = message ;
	    }
	
	    @Override
	    public String getMessage() {
	        return message;
	    }
	}

全局异常处理器

在整个 springMvc 系统里面只有一个!需要我们自己来开发,需要实现 org.springframework.web.servlet.HandlerExceptionResolver 接口 ;

思路:

全局异常处理器处理思路:解析出异常类型,判断是自定义异常还是运行时异常,如果是自定义异常则获取异常信息,如果是运行时异常,则显示 未知错误 ;

public class ExceptionResolver implements HandlerExceptionResolver {

    /**
     * 处理异常
     * @param request
     * @param response
     * @param handler 就是处理器对象。发生异常方法的处理器对象
     * @param ex 异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
       CustomerException customerException = null ;
       if (ex instanceof CustomerException){
           customerException = (CustomerException) ex;
       }else {
           customerException = new CustomerException("位置错误!") ;
       }

       ModelAndView modelAndView = new ModelAndView() ;
//       填充数据
        modelAndView.addObject("customerException",customerException);
//      绑定视图
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

配置全局异常处理器

springMvc.xml 文件中,加载之前写的 全局异常处理类

 <!--全局异常处理类-->
    <bean class="xin.ijava.ssm.exception.ExceptionResolver"/>

猜你喜欢

转载自blog.csdn.net/youngyouth/article/details/82780330