Я пытаюсь получить сообщение проверки после ошибки проверки объекта формы, поместить сообщение в ответ об ошибке и вернуть его, но я не смог выяснить, как выглядит множество статей и репозиториев 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");
}
ErrorResponse.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;
}
}
ProductForm.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, чтобы я не получил ошибку «несовместимые типы».