【Spring】自定义异常处理

每次系统出异常之后,我们不能每次都去看系统的报错信息,这样不一定会又快又准确地找到错误。这个时候,我们就需要定义一个自定义异常来帮助我们快速定位错误

首先我们编写一个JsonData类进行处理json请求的异常处理

@Data
public class JsonData {
    /*true表示正常,false表示异常*/
    private boolean ret;

    private String msg;

    private Object data;

    public JsonData(boolean ret){
        this.ret = ret;
    }

    /**
     * 成功
     * @param object
     * @param msg
     * @return
     */
    public static JsonData success(Object object,String msg){
        JsonData jsonData = new JsonData(true);
        jsonData.data = object;
        jsonData.msg = msg;
        return jsonData;
    }

    public static JsonData success(Object object){
        JsonData jsonData = new JsonData(true);
        jsonData.data = object;
        return jsonData;
    }

    /**
     * 失败
     * @param msg
     * @return
     */
    public static JsonData fail(String msg){
        JsonData jsonData = new JsonData(false);
        jsonData.msg = msg;
        return jsonData;
    }

    public Map<String,Object> toMap(){
        Map<String,Object> result = new HashMap<>();
        result.put("ret",ret);
        result.put("msg",msg);
        result.put("data",data);
        return result;
    }
}

接下来,我们自定义一个异常处理类SpringExceptionResolver实现HandlerExceptionResolver,并在spring-servlet.xml中进行配置

/**
 * @author evan_qb
 * @date 2018/8/8 10:25
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURI().toString();
        ModelAndView mv = null;
        String defaultMsg = "System error";
        //json请求或者页面请求 json数据以.json结尾,请求页面以.page结尾
        if (url.endsWith(".json")){
            if (e instanceof PermissionException){
                JsonData result = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());
            }else {
                log.error("unknow json exception,url:",url,e);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        }else if (url.endsWith(".page")){
            log.error("unknow page exception,url:",url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception",result.toMap());
        }else{
            log.error("unknow page exception,url:",url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}

spring-servlet.xml 中配置该类,使得每次请求都会进入该类进行处理,同时上面的jsonView也要在spring-servlet.xml中进行配置

<!--引入自定义异常处理器-->
<bean class="cn.qblank.common.SpringExceptionResolver" />
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />

然后我们定义一个自定义的异常类

/**
 * @author evan_qb
 * @date 2018/8/8 10:29
 */
public class PermissionException extends RuntimeException{
    public PermissionException() {
        super();
    }

    public PermissionException(String message) {
        super(message);
    }

    public PermissionException(String message, Throwable cause) {
        super(message, cause);
    }

    public PermissionException(Throwable cause) {
        super(cause);
    }

    protected PermissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

接下来我们编写TestController进行测试一下:

@GetMapping("/hello.json")
@ResponseBody
public JsonData hello(){
    log.info("hello");
    throw new PermissionException("test Exception");
    //return JsonData.success("hello world");
}

当我们抛出自定义的异常后,就能捕获到该异常,进入自定义异常处理器,输出对应的错误信息

当抛出其他类型的异常,自定义异常无法捕获时,进入自定义异常处理器,输出我们处理过后的信息,System error

@GetMapping("/hello.json")
@ResponseBody
public JsonData hello(){
    log.info("hello");
    throw new RuntimeException("test Exception");
    //return JsonData.success("hello world");
}

猜你喜欢

转载自blog.csdn.net/Evan_QB/article/details/81504682