Further to
- Java: what information in error stack trace do we typically not wish to show users? and
- How to manipulate SqlException message into user friendly message (C#)
I can either
duplicate each of my SQL table constraints in my Java code (e.g. explicitly run an SQL statement to check if a row being added has a primary key that already exists). Or
I can try to catch SQLExceptions in a common class/method that converts the exception into a message that makes sense to an end user.
The first seems like a lot of work. It also seems like unnecessary duplication. I still need the second approach as well in case some constraint gets overlooked or added without corresponding Java code. Or because there can be other types of SQLException (e.g. if the Ethernet lead falls out)
The trouble with the latter is that the exceptions are hard to parse. SQLException.getCause().getMessage() produces something like
The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'CURRENCY_PK' defined on 'CURRENCY'.
Obviously I'd prefer to have a message more like
Sorry, that currency code has already been defined, please edit the existing currency instead or use a different currency code for the currency you are adding.
I imagine the .getMessage()
text is likely to depend on the run-time environment and user language and other things. I don't see a way to get, for example, a numeric code that I could use to lookup my own user-friendly message.
Q: Is there a way to produce user-friendly messages in Java from SQLExceptions?