I have a domain class defined as follows
@Data
@Entity
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long cityID;
@NotBlank(message = "City name is a required field")
private String cityName;
}
When I post to the endpoint http://localhost:8080/cities
without a cityName I get a ConstraintViolationException but when I send a PUT request to the endpoint http://localhost:8080/cities/1
without a cityName I get the following exception instead of ConstraintViolationException.
{
"timestamp": 1494510208982,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.transaction.TransactionSystemException",
"message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction",
"path": "/cities/1"
}
So how do I get a ConstraintViolationException exception for a PUT request?
Note: I am using Spring Data Rest so the endpoints are generated by Spring. There is no custom rest controller.
I think Cepr0's test work for both PUT and POST, because when you send a PUT request for a non-existing entity then Spring Data Rest uses the create method in the background. Let's assume there is no user with id=100: calling 'PUT users/100' is the same as calling 'POST users/'
When you send PUT for an existing entity, it will generate that nasty TransactionSystemException.
I'm also fighting with the Data Rest exception-handling right now, and there are a lot of inconsistency in there.
Here is my current RestErrorAttributes class, it solves most of my problems, but there is a good chance I will fond others during the following days. :)
}
My workaround for this was to setup an exception handler to handle the
TransactionSystemException
, unwrap the exception and handle like a regularConstraintViolationException
: