通过自定义异常包装底层抛出的具体异常,统一对外返回结构化的错误响应。核心做法是在业务层捕获原始异常,将其封装为包含错误码和消息的自定义异常,再由全局异常处理器拦截并转换为json格式返回给客户端。

如何定义统一的异常转换机制
使用Spring Boot的全局异常处理功能,结合自定义注解或基类实现异常的自动转换。在控制器层抛出业务异常,由@RestControllerAdvice统一捕获并返回标准响应体。

public class BusinessException extends RuntimeException {
private String code;
private String message;
public BusinessException(String code, String message) {
super(message);
this.code = code;
this.message = message;
}
// getters...
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException ex) {
Map<String, Object> body = new HashMap<>();
body.put("code", ex.getCode());
body.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
}
上述代码定义了BusinessException作为业务异常的基类,并在GlobalExceptionHandler中捕获该异常,返回包含错误码和消息的JSON响应。开发者只需在业务逻辑中抛出BusinessException,即可实现统一的错误响应。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
如何将底层异常转换为业务异常
在Service层捕获底层异常(如数据库异常、网络异常等),并将其转换为BusinessException。这样可以隐藏底层实现的细节,只向客户端暴露业务相关的错误信息。

@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
try {
return userRepository.findById(id).orElseThrow(() -> new EntityNotFoundException("User not found"));
} catch (EntityNotFoundException e) {
throw new BusinessException("USER_NOT_FOUND", "用户不存在");
} catch (DataAccessException e) {
throw new BusinessException("DB_ERROR", "数据库访问失败");
}
}
}
在UserService中,捕获了EntityNotFoundException和DataAccessException,并将它们转换为BusinessException。这样,客户端只会收到统一的错误响应,而不会看到底层的异常堆栈信息。
当输入ID为负数时如何处理
如果传入的ID为负数,可以在Controller层进行参数校验,直接抛出BusinessException,避免进入Service层。
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
if (id <= 0) {
throw new BusinessException("INVALID_ID", "ID必须为正数");
}
return userService.getUserById(id);
}
在上述代码中,对id进行了校验,如果为负数则直接抛出BusinessException,返回错误码INVALID_ID和消息ID必须为正数。这样可以提前拦截非法输入,减少不必要的业务逻辑执行。

















