首页 > 技术文章 > SSM之全局异常处理器

lwx521 2018-04-14 14:19 原文

1. 异常处理思路

  首先来看一下在springmvc中,异常处理的思路: 
springmvc异常处理 
  如上图所示,系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。明白了springmvc中的异常处理机制,下面就开始分析springmvc中的异常处理。

 

2. 定义全局异常处理器

    1、定义自定义异常类,继承Exception

public class CustomException extends Exception {

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

    public CustomException(Throwable throwable){
        super(throwable);
        this.throwable = throwable;
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public void setThrowable(Throwable throwable) {
        this.throwable = throwable;
    }

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

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

2、定义异常处理器

public class CustomExceptionResolver implements HandlerExceptionResolver {


    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 解析出异常类型
        CustomException customException = null;
        String message = "";
        // 若该异常类型是系统自定义的异常,直接取出异常信息在错误页面展示即可。
        if(e instanceof CustomException){
            customException = (CustomException)e;
            customException.getThrowable().getClass().getName();
        }else{
            // 如果不是系统自定义异常,构造一个系统自定义的异常类型,信息为“未知错误”
            customException = new CustomException("未知错误");
            message = customException.getMessage();
        }
        //错误信息
        ModelAndView modelAndView = new ModelAndView();
        //将错误信息传到页面
        modelAndView.addObject("message",message);
        //指向错误页面
        modelAndView.setViewName("showError");
        return modelAndView;
    }
}

3、SpringMVC中配置全局异常处理器

 <bean class="com.smart.exception.CustomExceptionResolver"/>

4、测试

@RequestMapping(value="")
    @ResponseBody
    public Map<String,Object> Register(User user) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        try{
          boolean isSuccess = userService.Register(user);
          if(isSuccess){
             map.put("tip", "success");
          }
          else{
               map.put("tip", "error");
          }
        }catch (Exception e){
            throw new CustomException("未知错误");
        }
        return map;
    }

 

推荐阅读