全局异常捕获
- 首先定义全局异常处理器
/**
* 全局异常处理器,处理项目中抛出的业务异常
*/
@Slf4j
@RestControllerAdvice // 统一异常拦截(返回 JSON)
public class GlobalExceptionHandler {
/**
* 专门处理我们自定义的业务异常
*/
@ExceptionHandler(BaseException.class)
public Result<Void> handleBaseException(BaseException ex) {
log.warn("业务异常: {}", ex.getMessage());
// code 允许为 null,因此要判断
if (ex.getCode() != null) {
return Result.error(ex.getCode(), ex.getMessage());
}
// 如果没有 code,默认 500
return Result.error(ex.getMessage());
}
/**
* 处理所有未捕获的异常(兜底)
*/
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception ex) {
log.error("系统异常: ", ex);
return Result.error(500, "系统异常,请联系管理员");
}
}
2025/11/30大约 2 分钟
