如何实现ErrorCode枚举与CustomException集成并返回指定格式错误响应
完全可以实现该需求,按以下步骤操作即可:
1. 定义自定义运行时异常类
创建继承自RuntimeException的CustomException类,内部持有ErrorCode枚举实例,提供传入ErrorCode的构造方法:
package com.app.exception; import com.app.enums.ErrorCode; public class CustomException extends RuntimeException { private final ErrorCode errorCode; public CustomException(ErrorCode errorCode) { super(errorCode.getMessage()); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } }
注意根据你自己的项目包路径调整包名和ErrorCode的导入路径。
2. 配置全局异常拦截器
通过Spring提供的@RestControllerAdvice实现全局异常捕获,拦截抛出的CustomException,按照要求的格式组装响应结果:
package com.app.exception; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public Map<String, Object> handleCustomException(CustomException e, HttpServletRequest request) { Map<String, Object> errorResult = new HashMap<>(); errorResult.put("timestamp", System.currentTimeMillis()); errorResult.put("status", e.getErrorCode().getId()); errorResult.put("error", e.getErrorCode().getMessage()); errorResult.put("exception", e.getClass().getName()); errorResult.put("message", e.getErrorCode().getMessage()); errorResult.put("path", request.getRequestURI()); return errorResult; } }
如果需要同步设置HTTP响应状态码,可以将返回值改为ResponseEntity,根据业务码设置对应HTTP状态即可,注意非标准HTTP状态码可能被部分容器拦截,常规场景下HTTP状态码统一返回400、业务错误码放在返回体的status字段即可。
3. 修正原有业务代码的问题
你提供的Service层代码存在语法、逻辑错误,修正后参考如下:
import com.app.enums.ErrorCode; import com.app.exception.CustomException; import org.springframework.stereotype.Service; @Service public class UserService { public User add(long userId, String userName, String securityCode) { // 修正原代码的判空逻辑错误、字符串比较错误 if (securityCode != null && !securityCode.trim().isEmpty()) { // 编写你的业务逻辑,比如参数校验、用户数据落库等 User user = new User(); user.setUserId(userId); user.setUserName(userName); user.setSecurityCode(securityCode); return user; } else { // 修正原代码的拼写错误(threw→throw)、枚举引用错误 throw new CustomException(ErrorCode.SECURITYCODE_NOT_PROVIDED); } } }
Controller层代码不需要额外修改,CustomException属于运行时异常,不需要显式在方法上声明throws,保留原有声明也不会影响运行。
验证效果
启动服务后请求/api/user/add接口,当securityCode参数为空时,会返回和你要求格式完全一致的JSON响应,后续新增错误场景只需要在ErrorCode枚举中添加对应枚举值,在业务逻辑中抛出对应CustomException即可,全局拦截器会自动完成格式转换。
内容的提问来源于stack exchange,提问作者Musni
相关产品推荐
相关产品推荐

