记账软件教程之全局异常处理@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);
}