Spring boot 处理异常时返回错误响应

Spring boot 处理异常时返回错误响应,spring-boot,Spring Boot,弹簧靴 @RestController public class ProductsController { @PostMapping("/product") public ResponseEntity<Product> createProduct(@RequestBody String payload) { Product product = new Gson().fromJson(payload, Product.class);

弹簧靴

@RestController
public class ProductsController {
  @PostMapping("/product")
    public ResponseEntity<Product> createProduct(@RequestBody String payload) {
        Product product = new Gson().fromJson(payload, Product.class);
        checkProduct(product);
        product.setCreated(new Date());
        if (product.getPrice() == null) {
            throw new InvalidParameterException("Invalid price");
        }
        logger.info("createProduct: product:\n" + product);
        return new ResponseEntity<Product>(product, HttpStatus.OK);
    }
答复是:

   {
      "timestamp": "2020-09-08T23:25:25.514+00:00",
      "status": 500,
      "error": "Internal Server Error",
      "message": "",
      "path": "/api/v1/product"
}
但结果必须是:

 {
          "timestamp": "2020-09-08T23:25:25.514+00:00",
          "status": 400,
          "error": "Bad request",
          "message": "Invalid price",
          "path": "/api/v1/product"
    }
为什么不更正错误响应

我得到一个错误:

org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class myproject.model.ErrorResponse
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:230) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219) ~[spring-webmvc-

-也许这会有所帮助。@joy问题在于ErrorResponse中的一个嵌套对象没有任何getter/setter
 {
          "timestamp": "2020-09-08T23:25:25.514+00:00",
          "status": 400,
          "error": "Bad request",
          "message": "Invalid price",
          "path": "/api/v1/product"
    }
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class myproject.model.ErrorResponse
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:230) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219) ~[spring-webmvc-