You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Rest中如何通过ResponseEntity返回状态码与reasonPhrase?

解决Spring Boot响应中缺失ReasonPhrase/StatusDescription的问题

问题分析

你当前的@ExceptionHandler仅返回了响应体和状态码,但未显式设置状态行中的ReasonPhrase(如400对应的"Bad Request"),且Spring Boot部分内置服务器(如Undertow)默认禁用了ReasonPhrase的发送,导致VB.NET客户端无法获取该字段。

解决方案

1. 修改异常处理代码,手动设置ReasonPhrase

在异常处理方法中注入HttpServletResponse,通过它显式设置状态码和对应的ReasonPhrase:

/**
 * @param constrainedValueNotFoundException - exception object
 * @param response - HTTP响应对象
 * @return - ResponseEntity with http status code, error message and reason phrase
 */
@ExceptionHandler(value = ConstrainedValueNotFoundException.class)
public ResponseEntity<String> constrainedValueNotFoundException(
        ConstrainedValueNotFoundException constrainedValueNotFoundException,
        HttpServletResponse response) {
    logError(constrainedValueNotFoundException);
    // 设置状态码和对应的原因短语
    response.setStatus(HttpStatus.BAD_REQUEST.value());
    response.setReasonPhrase("Bad Request");
    return new ResponseEntity<>(
            constrainedValueNotFoundException.getLocalizedMessage(), HttpStatus.BAD_REQUEST);
}

2. 配置内置服务器,启用ReasonPhrase发送

根据你使用的内置服务器,添加对应配置:

若使用Undertow

在application.properties中添加:

server.undertow.enable-reason-phrase=true

若使用Jetty

在application.properties中添加(Spring Boot 2.4+版本支持):

server.jetty.send-reason-phrase=true

说明

HTTP/2规范中并不推荐使用ReasonPhrase,但出于兼容VB.NET客户端的需求,通过上述两步配置后,响应状态行将包含"400 Bad Request",客户端即可获取到期望的StatusDescription字段。

内容的提问来源于stack exchange,提问作者Sammy Pawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:59:57