springboot 统一异常处理.md
李羽秋
2022年01月26日 · 阅读 1,089
springboot 统一异常处理
由于接口返回的数据格式必须有固定的格式,方便调用者能够对不同异常进行统一的处理。
1.定义一个全局的异常类,继承Exception
public class GlobalException extends Exception{
private static final long serialVersionUID = -5701182284190108797L;
private int code;
public GlobalException(String message) {
super(message);
}
public GlobalException(String message, int code) {
super(message);
this.code =code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
2.根据自己的需求自定义响应码枚举类
public enum ResponseCode {
PARAM_ERROR_CODE(400),
SERVER_ERROR_CODE(500),
NOT_FIND_ERROR_CODE(404);
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
ResponseCode(int code) {
this.code = code;
}
}
3.根据不同的响应码创建相应的异常类
public class ServerException extends GlobalException{
private static final long serialVersionUID = -1355046108056594333L;
public ServerException(String message) {
super(message,ResponseCode.SERVER_ERROR_CODE.getCode());
}
}
public class ParamException extends GlobalException{
private static final long serialVersionUID = 6021390821349937519L;
public ParamException(String message) {
super(message,ResponseCode.PARAM_ERROR_CODE.getCode());
}
}
4.定义一个统一的接口返回格式类
public class ResponseData {
private Boolean status = true;
private int code = 200;
private String message;
private Object data;
public static ResponseData ok(Object data) {
return new ResponseData(data);
}
public ResponseData(Object data) {
super();
this.data = data;
}
public ResponseData() {
super();
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
5.定义一个全局异常处理Handler
在这里拦截异常,返回封装的统一的格式
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = GlobalException.class)
@ResponseBody
public ResponseData jsonErrorHandler(HttpServletRequest req,GlobalException e){
ResponseData r = new ResponseData();
r.setCode(e.getCode());
r.setData(null);
r.setMessage(e.getMessage());
r.setStatus(false);
return r;
}
}
6.模拟使用自定义异常
@GetMapping("/students/{name}")
Object queryStudentByName(@PathVariable String name) throws ParamException, ServerException {
if (name.equals("1")){
throw new ParamException("参数错误");
}
if (name.equals("2")){
throw new ServerException("服务器错误");
}
return "success";
}
7.测试
分类:
无
标签:
无