Spring Boot项目POST JSON校验失败时如何返回指定格式错误信息
Spring Boot POST接口JSON格式校验最优实现方案
1. 引入校验依赖
首先在pom.xml中引入Spring Boot校验启动器:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2. 定义请求DTO与规则
- DTO中不包含
id字段,由JPA实体层自动生成 - 加
@JsonIgnoreProperties(ignoreUnknown = false)禁止多余字段传入 - 字段上加校验注解指定必填规则
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = false) public class ProductRequestDTO { @NotBlank(message = "name字段不能为空") private String name; @NotBlank(message = "description字段不能为空") private String description; @NotNull(message = "price字段不能为空且必须为整数") private Integer price; // 省略getter、setter方法 }
对应的JPA实体类配置id自动生成:
import jakarta.persistence.*; @Entity @Table(name = "products") public class Product { @Id @GeneratedValue(strategy = GenerationType.UUID) private String id; private String name; private String description; private Integer price; // 省略getter、setter、构造方法 }
3. Controller层触发校验
POST接口参数前加@Valid注解触发校验规则:
import jakarta.validation.Valid; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/products") public class ProductController { private final ProductService productService; // 构造注入 public ProductController(ProductService productService) { this.productService = productService; } @PostMapping public ResponseEntity<Product> createProduct(@Valid @RequestBody ProductRequestDTO requestDTO) { Product savedProduct = productService.saveProduct(requestDTO); return ResponseEntity.ok(savedProduct); } }
4. 全局异常处理器统一返回错误格式
通过@RestControllerAdvice捕获所有校验相关异常,返回约定的错误结构:
首先定义错误响应实体:
public class ErrorResponse { private Integer code; private String error; public ErrorResponse(Integer code, String error) { this.code = code; this.error = error; } // 省略getter、setter方法 }
全局异常处理器代码:
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.http.converter.HttpMessageNotReadableException; @RestControllerAdvice public class GlobalValidationExceptionHandler { // 处理字段缺失、校验规则不匹配异常 @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidationError(MethodArgumentNotValidException e) { FieldError firstError = e.getBindingResult().getFieldError(); String errorMsg = firstError == null ? "参数校验失败" : firstError.getDefaultMessage(); return new ResponseEntity<>(new ErrorResponse(400, errorMsg), HttpStatus.BAD_REQUEST); } // 处理传入多余字段异常 @ExceptionHandler(UnrecognizedPropertyException.class) public ResponseEntity<ErrorResponse> handleExtraFieldError(UnrecognizedPropertyException e) { String errorMsg = String.format("存在不允许的多余字段: %s", e.getPropertyName()); return new ResponseEntity<>(new ErrorResponse(400, errorMsg), HttpStatus.BAD_REQUEST); } // 处理JSON格式错误、字段类型不匹配异常 @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity<ErrorResponse> handleJsonFormatError(HttpMessageNotReadableException e) { return new ResponseEntity<>(new ErrorResponse(400, "JSON格式错误或字段类型不匹配"), HttpStatus.BAD_REQUEST); } }
5. Service层实现存储逻辑
仅需完成DTO转实体、调用JPA保存即可,无需重复校验:
import org.springframework.stereotype.Service; @Service public class ProductService { private final ProductRepository productRepository; public ProductService(ProductRepository productRepository) { this.productRepository = productRepository; } public Product saveProduct(ProductRequestDTO requestDTO) { Product product = new Product(); product.setName(requestDTO.getName()); product.setDescription(requestDTO.getDescription()); product.setPrice(requestDTO.getPrice()); return productRepository.save(product); } }
额外配置说明
如果需要全局禁止多余字段,无需每个DTO加@JsonIgnoreProperties注解,可在application.properties中添加配置:
spring.jackson.deserialization.fail-on-unknown-properties=true
内容的提问来源于stack exchange,提问作者Vinicius Deluca
相关产品推荐
相关产品推荐

