前言
在做前后端分离项目中,前端请求的时候服务器发生错误,服务器会返回一堆错误信息,不规范也不好处理。再比如非前后端分离项目是,系统发生错误,也会直接返回一大堆错误信息给用户,导致页面非常的混乱不美观,我们也不需要用户知道发生了什么错误。只返回服务器错误即可。
1 、自定义异常类
@Data
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;
}
}
2、全局异常处理类
@RestControllerAdvice
@Log4j
public class AllExceptionHandler {
@ExceptionHandler(RRException.class)
public R handleRRException(RRException e){
int code = e.getCode();
String msg = e.getMsg();
log.error(msg);
for (StackTraceElement element : e.getStackTrace()){
log.error(element.toString());
}
R r = new R();
r.put("code" , code);
r.put("msg" , msg);
return r;
}
//如果需要处理其他的异常类 将这里的Exception替换就可以了
@ExceptionHandler(Exception.class)
public R handleException(Exception e){
String message = e.getMessage();
log.error(message);
//记录错误日志,输出到日志文件
for (StackTraceElement element : e.getStackTrace()){
log.error(element.toString());
}
}
return R.error("未知错误,请联系管理员")
}