I have a spring boot hibernate MySQL microservice and a web client that accesses the service via REST.
I have realized some database validations via hibernate annotations... e.g. not-null or unique.
Now, when the validation finds an error I get a stacktrace like this:
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a];
constraint [rahmenvertraege.UK_lla4el5s0eip4nwn8e3sd1trk]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not execute statement
...
...
...
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
....
...
...
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry
'Aktenzeichen XY0000000000000003333333333444444444245555555555f' for key 'rahmenvertraege.UK_lla4el5s0eip4nwn8e3sd1trk'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.21.jar:8.0.21]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.21.jar:8.0.21]
...
..
If I take the message of the exception and deliver it via the REST api to the client he gets the upper one "could not execute statement; SQL [n/a]; constraint [rahmenvertraege.UK_lla4el5s0eip4nwn8e3sd1trk]" which is not very inforamtiv.
The nested exception at the lowest position is the one that is interessting "Duplicate entry 'Aktenzeichen XY0000000000000003333333333444444444245555555555f' for key 'rahmenvertraege.UK_lla4el5s0eip4nwn8e3sd1trk'"
But how do I do that? Just always take the deepest nested exceptions message? Isnt that dirty? And how can the client (or the service layer of the micro service) can translate that for the client? Even if the deppest message is readable, its nothing that you want to present in the user interface. There you want to see something like "Name is already used. Please choose another one". Do I have to know all types of possible exceptions an map them manually?
Thanks for your ideas.