异常分为三大类
系统异常:系统运行、处理时发生的异常,捕获并返回友好提示
例如:空指针异常,参数为空
自定义异常:出现业务逻辑某处不符合要求,或不存在等,捕获并返回业务不符合信息
例如:未找到该用户,不存在
其他异常:未知的异常错误,友好给前端反馈信息
例如:未知错误
1、统一返回JSON实体
@Data
public class ResultBody<T> implements Serializable {
private Integer code;
private String message;
private T data; //不确定的数据类型
public ResultBody(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> ResultBody Success(Integer code, String message,T t){
return new ResultBody(code,message,t);
}
public static <T> ResultBody Error(Integer code, String message,T t){
return new ResultBody(code,message,t);
}
}
2、全局异常类
@Slf4j
@ControllerAdvice
public class ExceptionHander {
@ResponseBody
@ExceptionHandler(NullPointerException.class)
public ResultBody<String> nullPointerException(NullPointerException point){
log.error("发生空指针异常!{}");
return ResultBody.Error(400,"调用异常,参数不全!",null);
}
@ResponseBody
@ExceptionHandler(OrterExceptionHander.class) //该类为自定义异常类
public ResultBody<String> orterExceptionHander(OrterExceptionHander orterExceptionHander){
log.error("发生自定义异常原因:{}",orterExceptionHander.getMessage());
return ResultBody.Error(420,"自定义异常!",null);
}
}
注解说明:
@ControllerAdvice:表示一个增强类
@ResponseBody: 类似controller中的响应返回的JSON字符串
@ExceptionHandler:需要捕获的异常类
OrterExceptionHander为自定义异常,返回对应的实体类回去
3、自定义异常类
//继承RuntimeException:运行时异常
public class OrterExceptionHander extends RuntimeException {
//传值到父类,将需要返回的massage复制给父类,响应的时候拿出来getMessage()
public OrterExceptionHander(String message) {
super(message);
}
}
说明:
业务异常:throw new OrterExceptionHander("业务异常,没有找到id");
系统异常:会在全局异常中被捕获,如果没有定义改异常方法,是不会被拦截的。