异常分类:
分为系统异常和业务异常
系统异常:不可预知的异常,堆栈溢出、数据库报错。RuntimeException
业务异常:可预知的异常,某个参数没传、验证码没传、传的参数有问题。
之所以有这两种异常的原因是因为apm报警系统只拦系统异常。
异常拦截的目的:
规范化异常的处理过程,避免异常被吞和到处都在捕获异常的情况;对异常情况进行预警,以便能够及时响应
1、统一异常拦截:
@RestControllerAdvice//拦截所有的controller
@Slf4j
public class ExceptionAdvice {
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public JSONObject exceptionHandler(Exception e){
log.error("执行异常",e);
if(e instanceof MethodArgumentNotValidException){
MethodArgumentNotValidException exception= (MethodArgumentNotValidException) e;
return Result.getBusinessException(exception.getMessage(), ResponseStatus.BUSINESS_ERROR_STATUS.getCode()); //枚举类
}else if(e instanceof ChatException){
ChatException exception= (ChatException) e;
return Result.getBusinessException(exception.getMessage(),ResponseStatus.BUSINESS_ERROR_STATUS.getCode());
}else {
return Result.getBusinessException("后台异常,请联系管理员",ResponseStatus.BUSINESS_ERROR_STATUS.getCode());
}
}
其中,ResponseStatus是自己定义的枚举类,几乎能覆盖所有的异常
@Getter
@AllArgsConstructor
public enum ResponseStatus {
SUCCESS_STATUS("0","成功"),
BUSINESS_ERROR_STATUS("-1","业务异常"),
SERVICE_ERROR_STATUS("-2","系统异常"),
PARAM_ERROR_STATUS("-3","参数异常");
private String code;
private String desc;
}
2、非法sql拦截
作用:对不带where的 update 和 delete 语句的sql进行拦截,是mybatisPlus官方插件
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}