Spring Boot 自定义异常类
自定义异常类封装业务错误信息,配合全局异常处理实现精准的错误响应。
设计原则
- 继承RuntimeException(非受检异常)
- 包含错误码和错误信息
- 支持链式异常
基本实现
Java
public class BusinessException extends RuntimeException {
private final int code;
private final String message;
public BusinessException(int code, String message) {
super(message);
this.code = code;
this.message = message;
}
public BusinessException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
this.message = errorCode.getMessage();
}
public int getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
错误码枚举
Java
public enum ErrorCode {
USER_NOT_FOUND(1001, "用户不存在"),
USER_EXISTS(1002, "用户已存在"),
INVALID_PARAMETER(2001, "参数错误"),
UNAUTHORIZED(3001, "未授权"),
FORBIDDEN(3002, "禁止访问");
private final int code;
private final String message;
ErrorCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() { return code; }
public String getMessage() { return message; }
}
异常类层级设计
Java
// 基础业务异常
public class BusinessException extends RuntimeException { ... }
// 参数异常
public class ParameterException extends BusinessException {
public ParameterException(String message) {
super(ErrorCode.INVALID_PARAMETER.getCode(), message);
}
}
// 资源不存在异常
public class NotFoundException extends BusinessException {
public NotFoundException(String message) {
super(ErrorCode.USER_NOT_FOUND.getCode(), message);
}
}
全局异常处理集成
Java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Result> handleBusinessException(BusinessException e) {
return ResponseEntity.ok(Result.fail(e.getCode(), e.getMessage()));
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Result> handleNotFound(NotFoundException e) {
return ResponseEntity.status(404).body(Result.fail(e.getCode(), e.getMessage()));
}
}
使用示例
Java
@Service
public class UserService {
public User getById(Long id) {
User user = userRepository.findById(id);
if (user == null) {
throw new NotFoundException("用户不存在: " + id);
}
return user;
}
public void createUser(UserDTO dto) {
if (userRepository.existsByUsername(dto.getUsername())) {
throw new BusinessException(ErrorCode.USER_EXISTS);
}
// ...
}
}
要点总结
- 自定义异常继承RuntimeException
- 使用枚举统一管理错误码
- 按业务领域设计异常类层级
- 配合全局异常处理返回统一响应
📝 发现内容有误?点击此处直接编辑