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

如何在Spring Boot中自定义处理Required request body is missing异常返回

实现步骤

1. 编写全局异常处理器

Spring Boot 提供了@RestControllerAdvice注解用于全局拦截Controller抛出的异常,我们可以通过该组件捕获HttpMessageNotReadableException(请求体缺失时抛出的异常类型),自定义返回格式。
代码示例如下:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.converter.HttpMessageNotReadableException;
import java.util.Collections;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, String>> handleHttpMessageNotReadable(HttpMessageNotReadableException e) {
        String errMsg = e.getMessage();
        // 匹配请求体缺失的异常场景
        if (errMsg != null && errMsg.startsWith("Required request body is missing")) {
            return new ResponseEntity<>(Collections.singletonMap("message", "Required request body is missing"), HttpStatus.BAD_REQUEST);
        }
        // 其他请求体解析异常可在这里单独处理,或者走通用异常逻辑
        return new ResponseEntity<>(Collections.singletonMap("message", "请求参数解析失败"), HttpStatus.BAD_REQUEST);
    }
}

2. 可选配置:关闭默认错误返回的敏感信息

如果还有其他异常走Spring Boot默认错误返回的场景,可在application.yml(或application.properties)中添加如下配置,避免泄露栈追踪等敏感信息:

server:
  error:
    include-stacktrace: never # 永远不返回栈追踪信息
    include-exception: false # 不返回异常类名

3. 验证效果

配置完成后调用没有携带请求体的POST接口,即可得到目标返回格式:

{
    "message": "Required request body is missing"
}
注意事项
  • 请确认接口的@RequestBody注解没有手动设置required = false,否则请求体缺失时不会抛出对应异常,会直接进入Controller逻辑,需要自行判断请求体是否为null
  • 如果你项目中已经存在全局异常处理器,直接新增上述异常处理方法即可,不需要重复创建@RestControllerAdvice类

内容的提问来源于stack exchange,提问作者Hikaru Shindo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:06:00