记账软件教程之全局异常处理@RestControllerAdvice

记账软件教程之全局异常处理@RestControllerAdvice

在 Spring Boot 中,我们可以使用 @RestControllerAdvice 注解来统一处理异常。@RestControllerAdvice 注解可用于统一处理全局异常,其本质是一个 @ControllerAdvice 注解和 @ResponseBody 注解的组合。

使用 @RestControllerAdvice 进行异常处理非常方便。它可以为我们减少代码冗余,统一异常返回方式,提高应用程序的可维护性和可扩展性。

自定义异常

@EqualsAndHashCode(callSuper = true)
@Data
public class BizException extends RuntimeException {
    private static final long serialVersionUID = 123606337409762019L;

    /**
     * 错误码
     */
    private Integer code;

    public BizException(String msg) {
        super(msg);
        this.code = 10000;
    }
}

全局异常处理

加上注解: @RestControllerAdvice

使用@ExceptionHandler注解处理特定的异常类型

import com.llh.moneykeep.common.BizException;
import com.llh.moneykeep.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


/**
 * 异常拦截
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 参数验证失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        if (errors.isEmpty()) {
            return CommonResult.error(e.getMessage());
        }
        return CommonResult.error(errors.get(0).getDefaultMessage());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(BizException.class)
    public CommonResult<Object> bizException(BizException e) {
        return CommonResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<Object> exception(Exception e) {
        e.printStackTrace();
        return CommonResult.error(e.getMessage());
    }
}

使用

在处理业务的时候抛出异常,会在全局异常处理那里进行拦截,并且统一返回给前端。

throw new BizException(“用户名未注册”);

如下是一个登录方法

    public LoginResult login(LoginParam param) {
        // 查询用户是否注册
        List<User> userList = list(new LambdaQueryWrapper<User>()
        .eq(User::getUsername, param.getUsername())
        .eq(User::getIsDeleted, 0));
        if (CollUtil.isEmpty(userList)) {
        throw new BizException("用户名未注册");
        }
        User user = userList.get(0);

        // 验证密码是否正确
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean isPassword = passwordEncoder.matches(param.getPassword(), user.getPassword());
        if (!isPassword) {
        throw new BizException("密码错误");
        }

        // 生成令牌
        Map<String, Object> map = new HashMap<>(1);
        map.put("userId", String.valueOf(user.getId()));
        String token = JwtUtil.generateToken(map);
        return new LoginResult(token);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小虎哥的技术博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值