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

Spring Boot控制器中处理RequestBody JSON语法错误的注解方案

处理RequestBody JSON格式错误的友好提示方案

当客户端发送的请求体存在JSON语法错误时,Spring MVC会在控制器方法执行之前就抛出HttpMessageNotReadableException,这个异常不在你当前方法的try-catch范围内,所以无法被捕获处理。要解决这个问题,你需要使用全局异常处理器来统一处理这类请求解析阶段的异常。

具体实现步骤

1. 创建全局异常处理器类

使用@RestControllerAdvice(如果是返回视图场景用@ControllerAdvice)注解定义全局异常处理器,专门捕获JSON解析异常及其他全局异常:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.fasterxml.jackson.core.JsonParseException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理JSON格式错误/请求体解析失败的异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleJsonParseError(HttpMessageNotReadableException ex) {
        String message = "请求体JSON格式错误,请检查语法后重试";
        // 可选:获取Jackson解析的具体错误信息
        Throwable rootCause = ex.getRootCause();
        if (rootCause instanceof JsonParseException) {
            message = String.format("JSON解析错误:%s,请修正请求体格式", rootCause.getMessage());
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }

    // 处理@Valid参数校验失败的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidationErrors(MethodArgumentNotValidException ex) {
        List<String> errorDetails = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> String.format("%s:%s", error.getField(), error.getDefaultMessage()))
                .collect(Collectors.toList());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body("参数校验失败:" + String.join("; ", errorDetails));
    }

    // 处理业务逻辑异常(对应你原来的MediaValidationException和IllegalArgumentException)
    @ExceptionHandler({MediaValidationException.class, IllegalArgumentException.class})
    public ResponseEntity<String> handleBusinessExceptions(RuntimeException ex) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(ex.getMessage());
    }

    // 处理其他未捕获的全局异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请求处理失败,请检查请求参数");
    }
}

2. 简化控制器方法

既然全局异常处理器已经接管了所有异常处理,你可以移除控制器方法内的try-catch,让代码更简洁:

@PostMapping
public ResponseEntity<String> createMovie(@Valid @RequestBody Movie movie) {
    Movie newMovie = movieService.create(movie);
    return ResponseEntity.status(HttpStatus.CREATED).body(newMovie.toString());
}

关键说明

  • HttpMessageNotReadableException是Spring MVC在解析@RequestBody时抛出的异常,涵盖JSON语法错误、请求体为空等场景。
  • 全局异常处理器会拦截所有控制器的异常,无需在每个方法中重复编写异常处理逻辑,符合DRY原则。
  • 如果需要更定制化的错误响应(比如返回JSON格式的错误信息),可以把返回类型改成自定义的ErrorDTO对象,而不是String。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:05:15