自定义全局异常处理需要创建继承自 runtimeexception 的异常类,并在控制器中抛出该异常。spring boot 默认会自动捕获此类运行时异常并返回 http 500 状态码。若需自定义响应格式或状态码,可结合 @controlleradvice 和 @exceptionhandler 注解实现统一拦截。

如何定义一个携带错误码和消息的业务异常类
直接回答:创建一个继承自 RuntimeException 的类,添加 errorCode 和 message 字段,并提供构造函数即可。

public class BusinessException extends RuntimeException {
private final String errorCode;
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
如何在 Controller 中抛出并使用该异常
直接回答:在 Service 或 Controller 方法中使用 throw new BusinessException(...) 语句抛出异常,调用方无需显式捕获,由全局处理器接管。

@RestControllerAdvice











