Seeking help with Spring data validation to properly handle validation errors:
I am so confused by the docs regarding spring-data-rest validation here: http://docs.spring.io/spring-data/rest/docs/current/reference/html/#validation
I am trying to correctly handle validation for a POST call that is trying to save a new company object
I got this object:
@Entity public class Company implements Serializable { @Id @GeneratedValue private Long id; @NotNull private String name; private String address; private String city; private String country; private String email; private String phoneNumber; @OneToMany(cascade = CascadeType.ALL, mappedBy = "company") private Set<Owner> owners = new HashSet<>(); public Company() { super(); }
...
and this parameter is RestResource dao
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RestResource; import com.domain.Company; @RestResource public interface CompanyDao extends PagingAndSortingRepository<Company, Long> { }
POST Request for api / Companies:
{ "address" : "One Microsoft Way", "city" : "Redmond", "country" : "USA", "email" : "info@microsoft.com", "phoneNumber" : "(425) 703-6214" }
When I issue a POST with a null name, I get the following rest response with httpcode 500
{"timestamp": 1455131008472, "status": 500, "error": "Internal Server Error", "exception": "javax.validation.ConstraintViolationException", "message": "Validation error for classes [com. domain.Company ] during save for groups [javax.validation.groups.Default,] \ nList restriction violations: [\ n \ tConstraintViolationImpl {interpolationMessage = 'cannot be null ", propertyPath = name, rootBeanclass = class com.domain.Company, messageTemplate = '{javax.validation.constraints.NotNull.message}'} \ n] "," path ":" / api / companies / "}
I tried to create the following bean, but it never does anything:
@Component(value="beforeCreateCompanyValidator") public class BeforeCreateCompanyValidator implements Validator{ @Override public boolean supports(Class<?> clazz) { return Company.class.isAssignableFrom(clazz); } @Override public void validate(Object arg0, Errors arg1) { System.out.println("xxxxxxxx"); } }
and even if it worked, how would it help me develop a better answer to the error with the proper http code and clear json answer?
so confusing
using 1.3.2.RELEASE
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>