@exceptionhandler(businessexception.class)不会自动解析errorcode,需在businessexception中提供geterrorcode()方法,并在处理器中调用该方法获取code,封装进统一errorresponse返回,且应将处理器置于@controlleradvice类中实现全局生效。

在 Java Spring Boot 中,@ExceptionHandler(BusinessException.class) 本身不会自动解析自定义异常中的 errorCode,你需要手动从异常对象中获取该字段,并在响应中使用它。
确保 BusinessException 暴露 errorCode 字段
你的自定义异常类必须提供公开的访问方式(如 getter 方法或 public 字段),否则处理器无法读取 errorCode:
- 推荐用 getter:在
BusinessException中定义public String getErrorCode() { return errorCode; } - 避免直接暴露 public 字段(违反封装原则)
- 确保构造时正确赋值,例如:
super(message); this.errorCode = errorCode;
在 @ExceptionHandler 方法中提取并使用 errorCode
在异常处理器方法里,把参数声明为 BusinessException 类型,然后调用其 getter 获取 errorCode:
- 示例方法签名:
public ResponseEntity<errorresponse> handleBusinessException(BusinessException ex)</errorresponse> - 在方法体内写:
String code = ex.getErrorCode(); - 将
code封装进返回对象(如ErrorResponse)中,再构建ResponseEntity
统一响应结构建议
为保持 API 一致性,建议定义一个标准错误响应体,包含 code、message、timestamp 等字段:
-
ErrorResponse类中字段名尽量与前端约定一致(如errCode或code) - 避免在 handler 中硬编码状态码,优先根据业务场景设置 HTTP 状态(如 400、409、500)
- 可配合
@ResponseStatus注解设定默认状态,但动态状态仍需在方法内控制
注意全局异常处理器的优先级和范围
@ExceptionHandler 默认只处理当前 controller 内抛出的异常。若要全局生效:
- 把方法放在
@ControllerAdvice类中 - 确认该类被 Spring 扫描到(如加
@Component或位于主启动类同包下) - 多个
@ExceptionHandler方法之间按类型匹配,子类异常可被父类 handler 捕获,注意继承关系
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











