spring-boot,全局异常统一拦截处理

原创 2018-12-13 10:32:00 JAVA 阅读(187)

简介 在项目中,我们一半返回到前端数据都是保持一致性,在出现异常信息的时候同样保持一致性,而且有时候业务处理需要自定义的一些异常返回给前端,这时候就需要我们对异常做统一的拦截处理了。

1、创建自定义的异常RRException

package com.blog.common.utils; /** * @author wangfj * @date 2018-11-19 * @description 自定义异常 */ public class RRException extends RuntimeException { private static final long serialVersionUID = 1L; private String msg; private int code = 500; private Object data; public Object getData() { return data; } public void setData(Object data) { this.data = data; } public RRException(String msg) { super(msg); this.msg = msg; } public RRException(String msg, Throwable e) { super(msg, e); this.msg = msg; } public RRException(String msg, int code) { super(msg); this.msg = msg; this.code = code; } public RRException(String msg, int code, Throwable e) { super(msg, e); this.msg = msg; this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }

2、创建异常处理配置类MyExceptionHandler

package com.blog.index.config; import com.blog.common.result.R; import com.blog.common.utils.RRException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * @author wangfujie * @date 2018-12-12 16:45 * @description 全局异常捕获处理 */ @ControllerAdvice public class MyExceptionHandler { /** * 统一异常处理 * @param e * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Object errorHandler(Exception e){ e.printStackTrace(); return R.error(110, e.getMessage()); } /** * 自定义异常的处理 * @param e * @return */ @ResponseBody @ExceptionHandler(value = RRException.class) public Object myErrorHandler(RRException e){ e.printStackTrace(); return R.error(e.getCode(), e.getMsg()); } }

3、在代码中手动抛出异常即可

throw new RRException("该用户没有权限!", 504);

4、返回效果

{"msg":"该用户没有权限!","code":504,"needRefresh":true}

image.png