之前项目的异常是一层一层抛出去及其麻烦,并且每个层都要try catch 然后把错误信息包装返回到最顶层 ,从service一层一层抛出去。人都写傻了,后面发现了springboot项目有全局拦截器。还是看的太浅了,先随便创建一个
全局拦截MyControllerAdvice.java
/**
* controller 增强器
*/
@ControllerAdvice
public class MyControllerAdvice {
/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = RrException.class)
public Result errorHandler(RrException ex) {
return Result.error(ex.getMessage());
}
}
其中的RrException 是我自定义的异常 因为我自己要抛出 但是Exception又需要捕捉 ,而自定义的错误就不用
异常类RrException .class
/**
* 自定义异常
* @author zyc
*/
public class RrException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
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;
}
}
这样在
这样后端报的错误就会被拦截然后返回一个Result对象到前端
结果类Result.class
public class Result extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public Result() {
put("code", 0);
put("msg", "success");
}
public static Result error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
}
public static Result error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static Result error(int code, String msg) {
Result r = new Result();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static Result ok(String msg) {
Result r = new Result();
r.put("msg", msg);
return r;
}
public static Result ok(Map<String, Object> map) {
Result r = new Result();
r.putAll(map);
return r;
}
public static Result ok() {
return new Result();
}
@Override
public Result put(String key, Object value) {
super.put(key, value);
return this;
}
}
参考自https://www.jianshu.com/p/383725700b7b
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/2190.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...