我试图从表单对象验证失败中获取验证消息,将该消息放入错误响应中并返回它,但我无法弄清楚如何查看大量文章和 github 存储库...
ProductController.java
@PostMapping("/products")
public ProductResponse createProduct(@Validated @RequestBody ProductForm productForm, BindingResult bindingResult) {
//trying to make the code below work but I get an "incompatible type" error.
if (bindingResult.hasErrors()) {
List<String> errors = bindingResult.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());
return new ErrorResponse("404", "Validation failure", errors);
}
Product product = productForm.convertToProduct();
Product createdProduct = productRepository.save(product);
return new ProductResponse(createdProduct, "Product created");
}
错误响应.java
package com.assignment.restapi.web.response;
import java.util.ArrayList;
import java.util.List;
public class ErrorResponse {
private String statusCode;
private String errorContent;
private List<String> messages;
public ErrorResponse(String statusCode, String errorContent, String messages) {
this.statusCode = statusCode;
this.errorContent = errorContent;
this.messages = new ArrayList<>();
this.messages.add(messages);
}
public ErrorResponse(String statusCode, String errorContent, List<String> messages) {
this.statusCode = statusCode;
this.errorContent = errorContent;
this.messages = messages;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getErrorContent() {
return errorContent;
}
public void setErrorContent(String errorContent) {
this.errorContent = errorContent;
}
public List<String> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
}
产品表单.java
package com.assignment.restapi.web.view;
import com.assignment.restapi.domain.Product;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class ProductForm {
String productImage;
@NotBlank(message = "cannot be blank")
@Size(max = 100, message = "has to be over 100 characters")
String productTitle;
@Size(max = 500, message = "has to be over 500 characters")
String productDescription;
@Min(value = 1, message = "has to be larger than 1")
Integer productPrice;
public ProductForm() {
}
public ProductForm(String productImage, String productTitle, String productDescription, Integer productPrice) {
this.productImage = productImage;
this.productTitle = productTitle;
this.productDescription = productDescription;
this.productPrice = productPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductTitle() {
return productTitle;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public Integer getProductPrice() {
return productPrice;
}
public void setProductPrice(Integer productPrice) {
this.productPrice = productPrice;
}
//turns productForm into Product object.
public Product convertToProduct() {
//step by step debug mode, new object constructor function in Product.java gets called.
//setter methods get called and values of the ProductForm object gets passed and becomes the new value of the Product object.
Product product = new Product();
product.setProductTitle(this.productTitle);
product.setProductImage(this.productImage);
product.setProductDescription(this.productDescription);
product.setProductPrice(this.productPrice);
return product;
}
}
知道当表单对象出现验证错误时如何返回 ErrorResponse 吗?
正在考虑创建一个扩展 ErrorResponse 和 ProductResponse 类的类,这样我就不会收到“不兼容类型”的错误。
最佳答案
您收到“不兼容类型”的原因是该方法预计返回“ProductResponse”,但您试图返回“ErrorResponse”。这可以通过使用 ResponseEntity 来解决。
@PostMapping("/products")
public ResponseEntity<Object> createProduct(@Validated @RequestBody ProductForm productForm, BindingResult bindingResult) {
//trying to make the code below work but I get an "incompatible type" error.
if (bindingResult.hasErrors()) {
List<String> errors = bindingResult.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());
// Here you can change ok to badRequest depending on your use case.
return ResponseEntity.ok(new ErrorResponse("404", "Validation failure", errors));
// In case if you want to fail the request, you need to use the below:
// return ResponseEntity.badRequest().body(new ErrorResponse("404", "Validation failure", errors));
}
Product product = productForm.convertToProduct();
Product createdProduct = productRepository.save(product);
return ResponseEntity.ok(new ProductResponse(createdProduct, "Product created"));
}
关于java - 如何从绑定(bind)结果验证失败返回错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006227/