在我们写项目时候,肯定会遇到各种各样的异常报错和用户传值错误需要返回对应的错误提示,如果我们都手动进行返回Result对象的话就会出现两个比较麻烦的问题:
所以在大项目中使用全局异常处理,是很有必要的!
1、自定义一个实体类
@Getter
public class BusinessException extends RuntimeException {
private final int code;
private final String description;
public BusinessException(String message, int code, String description) {
super(message);
this.code = code;
this.description=description;
}
public BusinessException(ResultCode resultCode, String description) {
super(resultCode.getMsg());
this.code = resultCode.getCode();
this.description=description;
}
}
2、定义一个全局异常捕捉类
@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResultUtil businessExceptionHandler(BusinessException e){
log.error("BusinessException:{}",e);
return ResultUtil.failed(e.getCode(),e.getMessage(),e.getDescription());
}
@ExceptionHandler(RuntimeException.class)
public ResultUtil runtimeExceptionHandler(RuntimeException e){
log.error("RuntimeException:{}",e);
return ResultUtil.failed(ResultCode.SYSTEM_ERROR,e.getMessage());
}
}
这样我们系统总所有的BusinessException和RuntimeException就都会被这个类捕捉,并统一返回Result给前端
例如:
if (StringUtils.isAnyBlank(userAccount, userPassword)) {
throw new BusinessException("格式错误",500,"用户名或密码为空");
}