如何修改Spring中ResponseStatusException的error键值
解决Spring ResponseStatusException自定义error字段的方案
方案一:自定义ErrorAttributes(推荐)
Spring Boot通过ErrorAttributes接口生成错误响应的JSON结构,默认实现是DefaultErrorAttributes。我们可以重写它的方法来修改error字段的值:
- 创建自定义ErrorAttributes类:
import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.web.context.request.WebRequest; import org.springframework.web.server.ResponseStatusException; import java.util.Map; public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options); Throwable error = getError(webRequest); // 针对ResponseStatusException替换error字段 if (error instanceof ResponseStatusException) { errorAttributes.put("error", "custom error"); // status字段保留原异常的状态码,无需修改 } return errorAttributes; } }
- 注册自定义类到Spring容器:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ErrorConfig { @Bean public CustomErrorAttributes customErrorAttributes() { return new CustomErrorAttributes(); } }
这样抛出ResponseStatusException时,响应里的error字段会被替换为"custom error",message字段依然保留你通过构造器设置的内容。
方案二:全局异常处理器直接构建响应
通过@RestControllerAdvice实现全局异常处理,完全掌控响应输出结构:
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.server.ResponseStatusException; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResponseStatusException.class) public ResponseEntity<Map<String, Object>> handleResponseStatusException(ResponseStatusException ex) { Map<String, Object> response = new HashMap<>(); response.put("status", ex.getStatusCode().value()); response.put("error", "custom error"); // 自定义error字段 response.put("message", ex.getMessage()); // 保留原message response.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(response, ex.getStatusCode()); } }
这种方式不需要修改框架默认的错误处理逻辑,直接拦截ResponseStatusException并返回自定义结构的响应。
内容的提问来源于stack exchange,提问作者bkevk
相关产品推荐
相关产品推荐

