SpringBoot统一异常处理
统一异常处理
需要:
- 一个信息码(code)和对应的异常信息(msg)
- 一个自定义异常 APIException
- 一个统一异常类 CommonExceptionAdvice
- 统一的返回对象 APIResult
1. CodeMsg对象
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CodeMsg {
private Integer code;
private String msg;
}
2. 自定义异常对象 APIException
@NoArgsConstructor
@Setter
@Getter
public class APIException extends RuntimeException{
private CodeMsg codeMsg;
public APIException(CodeMsg codeMsg){
super(codeMsg.getMsg());
}
}
3. 统一异常类 CommonExceptionAdvice
/*
@ControllerAdvice : 对Controller所抛出的异常进行处理
@ExceptionHandler(APIException.class) : 指明这个异常处理的方法是处理那种类型的异常
*/
@ControllerAdvice
public class CommonExceptionAdvice {
@ExceptionHandler(APIException.class)
public Result hanlderBusinessException(APIException ex){
return APIResult.error(ex.getCodeMsg()); //将信息码和信息返回
}
}
4.统一的返回对象 APIResult
@Data
@AllArgsConstructor
@NoArgsConstructor
public class APIResult<T> implements Serializable{
//自定义的信息码和信息
public static final int SUCCESS_CODE = 200;
public static final int SUCCESS_ERROR = 500;
public static final String SUCCESS_MSG = "操作成功";
public static final String ERROR_MSG = "系统繁忙,稍后再试";
private int code;
private String msg;
private T data;
//正常情况需要传返回数据
public static <T> APIResult success(T data){
return new APIResult(SUCCESS_CODE,SUCCESS_MSG,data);
}
//默认异常
public static APIResult defaultError(){
return new APIResult(SUCCESS_ERROR,ERROR_MSG,null);
}
//异常的话没有数据,就不需要传data
public static APIResult error(CodeMsg codeMsg){
return new APIResult(codeMsg.getCode(),codeMsg.getMsg(),null);
}
}

浙公网安备 33010602011771号