SpringBoot开发系列--全局异常处理:@RestControllerAdvice作用及原理

使用springboot开发系统时,假设还是登录功能的实现,如果此时让你校验用户名(手机号)是否为空或者是否合法,传统意义上会使用下面的逻辑

if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
//手机哈为空或者密码为空,返回json数据供前端接受解析提示
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if(!ValidatorUtil.isMobile(mobile)){
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

但是如果我们遇到自定义模板,或者处理一些特定的异常时,比如全局异常,这种方法显然是无法满足需求的。今天就介绍一个方法,捕捉全局异常,并对异常进行处理。
我们首先定义全局异常处理类如下:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public RespBean  ExceptionHandler(Exception e){
        if(e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        }else if(e instanceof BindException){
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.LOGIN_ERROR);
            respBean.setMessage("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}

其中两个注解含义如下:
@RestControllerAdvice:监控所有Controller类中抛出的异常,@RestControllerAdvice = @ControllerAdvice+@ResponseBody,看到这里,相信大家都懂了。
@ExceptionHandler(value = ExceptionType.class):对异常为ExceptionType类型的异常进行处理的方法。

public RespBean ExceptionHandler()里面对GlobalException(自己定义的异常)和BindException进行了处理,你可以根据自己的需要进行更改。

编写好GlobalExceptionHandler 类之后,在controller中,遇到一些全局异常,我们可以直接这样做:

User user = userMapper.selectById(mobile);
        if (null==user){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        if (!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

这样GlobalExceptionHandler 类便会对此进行截获处理。
由于代码是项目中的,截取的片段,如果想测试,可参考下面的博客:
@RestControllerAdvice

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三喂树屋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值