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

SpringBoot Java11中如何处理@Valid注解场景下的非格式JSON请求

解决SpringBoot非法JSON请求无提示的问题

当请求体是非法JSON时,SpringBoot会在进入控制器前触发Jackson的解析异常,默认只返回400状态码,没有友好提示。以下两种轻量方案可以解决,不用过度设计:

方案1:自定义全局异常处理器(精准控制)

写一个全局异常处理器,专门捕获JSON解析相关的异常,返回自定义的友好提示:

import com.fasterxml.jackson.core.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class JsonParseExceptionHandler {

    // 直接捕获Jackson的解析异常
    @ExceptionHandler(JsonParseException.class)
    public ResponseEntity<ErrorResp> handleJsonParseError(JsonParseException e) {
        ErrorResp resp = new ErrorResp();
        resp.setCode(HttpStatus.BAD_REQUEST.value());
        resp.setMessage("请求JSON格式无效:" + e.getOriginalMessage());
        return new ResponseEntity<>(resp, HttpStatus.BAD_REQUEST);
    }

    // 捕获Spring包装后的HttpMessageNotReadableException(兼容更多场景)
    @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
    public ResponseEntity<ErrorResp> handleMessageNotReadableError(org.springframework.http.converter.HttpMessageNotReadableException e) {
        String msg = "请求JSON格式无效";
        if (e.getCause() instanceof JsonParseException) {
            msg += ":" + ((JsonParseException) e.getCause()).getOriginalMessage();
        }
        ErrorResp resp = new ErrorResp();
        resp.setCode(HttpStatus.BAD_REQUEST.value());
        resp.setMessage(msg);
        return new ResponseEntity<>(resp, HttpStatus.BAD_REQUEST);
    }

    // 自定义简单的错误响应类
    static class ErrorResp {
        private int code;
        private String message;

        // Getter & Setter
        public int getCode() { return code; }
        public void setCode(int code) { this.code = code; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
}

这个方案只需要新增一个类,不改动原有业务代码,能精准控制返回的提示内容,不会泄露其他异常的敏感信息。

方案2:配置SpringBoot错误响应(快速实现)

如果不需要自定义响应格式,只想快速返回错误信息,可以在配置文件里添加:

application.properties:

server.error.include-message=always
server.error.include-binding-errors=always

application.yml:

server:
  error:
    include-message: always
    include-binding-errors: always

配置后,SpringBoot会自动返回包含异常信息的响应,但这个设置对所有错误生效,如果不想暴露其他异常的细节,优先选方案1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:47:10