Assert.notNull 断言报错自定义返回api格式
在 Spring Boot 中,当 Assert.notNull 抛出 IllegalArgumentException 时,我们可以通过全局异常处理来捕获并返回自定义的 API 格式。以下是几种实现方式:
使用 @RestControllerAdvice 全局异常处理(推荐)
自定义统一返回格式
ApiResult.java
// 统一返回结果类
@Data
public class ApiResult {
private Integer code;
private String message;
private T data;
private Long timestamp;
public ApiResult() {
this.timestamp = System.currentTimeMillis();
}
public static ApiResult success(T data) {
ApiResult result = new ApiResult<>();
result.setCode(200);
result.setMessage("success");
result.setData(data);
return result;
}
public static ApiResult error(Integer code, String message) {
ApiResult result = new ApiResult<>();
result.setCode(code);
result.setMessage(message);
result.setData(null);
return result;
}
public static ApiResult error(String message) {
return error(500, message);
}
}
全局异常处理器
exception 目录 GlobalExceptionHandler.java
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
// 处理 IllegalArgumentException(Assert.notNull 抛出的异常)
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResult handleIllegalArgumentException(IllegalArgumentException e) {
log.error("捕获到IllegalArgumentException: {}", e.getMessage()); // 添加日志
return ApiResult.error(400, e.getMessage());
}
//业务异常处理器,可用于手动 throw new BusinessException(400, message);
@ExceptionHandler(BusinessException.class)
public ApiResult handleBusinessException(BusinessException e) {
log.error("捕获到BusinessException: {}", e.getMessage());
return ApiResult.error(e.getCode(), e.getMessage());
}
// 处理其他异常
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiResult handleException(Exception e) {
log.error("捕获到Exception: {}", e.getMessage(), e); // 打印堆栈
return ApiResult.error(500, "系统异常:" + e.getMessage());
}
}
业务异常处理器,可用于手动 throw new BusinessException(400, message);
exception 目录 BusinessException.java
// 自定义业务异常类
@Data
@EqualsAndHashCode(callSuper = true)
public class BusinessException extends RuntimeException {
private Integer code;
private String message;
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
this.message = message;
}
}
在全局异常处理器中添加 BusinessException 处理
上面已经加了,这里仅加深印象
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ApiResult handleBusinessException(BusinessException e) {
return ApiResult.error(e.getCode(), e.getMessage());
}
// ... 其他异常处理
}
3. 使用示例
Controller 层示例
UserController.java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public ApiResult login(@RequestBody LoginRequest request) {
// 使用 Spring 的 Assert
Assert.notNull(request.getUsername(), "用户名不能为空");
Assert.notNull(request.getPassword(), "密码不能为空");
// 或者使用自定义断言
CustomAssert.notNull(request.getUsername(), 400, "用户名不能为空");
User user = userService.login(request);
return ApiResult.success(user);
}
@GetMapping("/detail")
public ApiResult> getUser(@RequestParam(name = "id",required = false) Long id) {
// 使用 Spring 的 Assert
// 仅测试,所以required = false,required = true会触发全局错误
Assert.notNull(id, "用户ID不能为空");
return ApiResult.success("user");
}
}
Service 层示例
UserService.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser(Long id) {
// 参数校验
Assert.notNull(id, "用户ID不能为空");
return userRepository.findById(id)
.orElseThrow(() -> new BusinessException(404, "用户不存在"));
}
}
4. 自定义异常消息格式
如果希望统一 Assert 的错误消息格式:
java
public class ErrorMessages {
public static final String NOT_NULL = "%s不能为空";
public static final String NOT_BLANK = "%s不能为空字符串";
public static final String NOT_EMPTY = "%s不能为空集合";
}
// 使用方式
Assert.notNull(userId, String.format(ErrorMessages.NOT_NULL, "用户ID"));
这样配置后,Assert.notNull 抛出的异常会被全局异常处理器捕获,并返回统一的 API 格式:
json
{
"code": 400,
"message": "用户名不能为空",
"data": null,
"timestamp": 1635769200000
}

