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

Spring Boot请求体缺失时如何自定义异常返回POJO类型ResponseEntity

问题根因

默认情况下@RequestBody注解的required属性为true,请求未携带JSON请求体时,Spring MVC会在参数绑定阶段直接抛出HttpMessageNotReadableException,不会进入你的接口方法逻辑,所以你写的空校验和自定义异常抛出代码根本不会执行。

可选解决方案

方案1:调整参数属性+自定义异常校验

适合需要在接口内做自定义空判断逻辑的场景:

  1. 修改接口参数注解,设置请求体非必填:
    把原有方法的参数@RequestBody DataRequest json改为@RequestBody(required = false) DataRequest json,此时如果请求未传请求体,json参数会赋值为null,可以进入方法内的校验逻辑。
  2. 方法开头增加空判断抛出自定义异常:
    @PostMapping(value="/postdata",produces = MediaType.APPLICATION_JSON_VALUE)
    private ResponseEntity<DataResponse> postData(@RequestBody(required = false) DataRequest json) throws JsonProcessingException {
        // 新增空校验
        if (json == null) {
            throw new UserDefinedException("Request Body is needed");
        }
        // 原有业务逻辑...
    }
    
  3. 新增全局异常处理器捕获自定义异常,返回指定JSON格式:
    @RestControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(UserDefinedException.class)
        public ResponseEntity<Map<String, String>> handleUserDefinedException(UserDefinedException e) {
            Map<String, String> result = new HashMap<>();
            result.put("msg", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
    }
    

方案2:全局捕获请求体缺失异常(无需修改原有接口代码)

适合所有POST接口统一处理请求体缺失的场景,无需逐个调整接口参数:
直接新增全局异常处理器,捕获Spring抛出的HttpMessageNotReadableException,匹配请求体缺失的异常信息后返回指定格式:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, String>> handleHttpMessageNotReadable(HttpMessageNotReadableException e) {
        Map<String, String> result = new HashMap<>();
        if (e.getMessage() != null && e.getMessage().contains("Required request body is missing")) {
            result.put("msg", "Request Body is needed");
        } else {
            result.put("msg", "请求参数格式非法");
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }
}
额外注意事项

你贴出的原有代码存在两处语法错误,需要自行修正:

  • 重复定义data变量,你先声明了DataResponse data = null,后面又定义了String data = jobj.getJSONObject("data").toString()
  • 方法最后返回的segment变量未定义,应该返回你转换后的data对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:54:04