异常拦截=

异常分类:

分为系统异常和业务异常

系统异常:不可预知的异常,堆栈溢出、数据库报错。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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值