Reputation: 5674
I have a (REST) application that handles CRUD operations initiated by a 3rd party, and basically my problem is in returning an easily understood error message in the case of a constraint violation. I'm using Hibernate (though JPA solutions would be better) and the ConstraintViolationException it throws is not terribly useful, it doesn't even have the name of the constraint that has been violated. I've so far been returning constraintViolation.getSQLException().getMessage()
which returns a half decent message along the lines of Duplicate entry '<value>' for key 2
.
The problem is a new requirement to improve the error returned to include which entity failed to commit as well as the value (and what kind of failure it was as a custom error code; DUPLICATE_VALUE, MISSING_FOREIGN_KEY, or something like that). Since the above string comes from the SQLException I assume it depends on the DB/driver, so while I could pick out '' from that string and search through every field in every object I just committed to try to find the right one it doesn't exactly seem the robust option (especially as we need to support multiple databases).
So is there any way I can find this information based on the information at hand? (Which is basically just the ConstraintViolationException w/SQLException and the object I tried to persist).
Upvotes: 1
Views: 189
Reputation: 2635
It should be possible to capture that exception specifically and return a meaningful response, instead of generic exceptions and parsing it to understand , it's worth the effort to re-factor this. just my 2c's
Upvotes: 0
Reputation: 32969
This is why you should validate provided data in business logic rather than depending on Hibernate to do it. Web frameworks provide validation mechanisms for just this reason.
Upvotes: 1