From: | Craig Ringer <craig(at)postnewspapers(dot)com(dot)au> |
---|---|
To: | Kris Jurka <books(at)ejurka(dot)com> |
Cc: | Thomas Finneid <tfinneid(at)fcon(dot)no>, pgsql-jdbc(at)postgresql(dot)org |
Subject: | Re: jdbc excpetions in pg |
Date: | 2009-06-04 00:28:18 |
Message-ID: | 4A271522.2080003@postnewspapers.com.au |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-jdbc |
Kris Jurka wrote:
>> If so, what is the suggested method for classifying the errors to more
>> detail than SQLException? I was hoping to make my code more robust by
>> dealing with the errors more appropriately.
>
> You should check the SQLState of the SQLException to determine the type
> of problem encountered.
For many errors the PostgreSQL driver throws an exception that's wrapped
into the SQLException. This org.postgresql.util.PSQLException contains
additional details like the server error message.
I put together the attached class as a helper/utility to provide a
convenient way to get the simplest error message to summarize a given
error. It was written before it became possible to select your own
SQLState when raising exceptions in PL/PgSQL, and I need to adapt it to
make better use of that ability, but it's still handy, as it lets me
write things like:
JOptionPane.showMessageDialog(
parentFrame,
"Your changes have not been saved because an error" +
" occurred while trying to save them.\n" +
"You may be able to correct the problem described " +
"below and press 'save' again.\n\n" +
"Problem details: " + DbExceptionUtil.getDbErrorMsg(e),
"Unable to save changes to customer",
JOptionPane.ERROR_MESSAGE);
without worrying about whether the issue was a Hibernate validation
exception, an error thrown from PL/PgSQL, a constraint check, etc. With
the use of human-readable constraint names, I find this works rather well.
Of course, you should __NEVER__ test the error message text or make
decisions based on the error message text in your code. Rely solely on
exception type and SQLState for that, since they're unaffected by
translations, small changes in wording across versions, etc.
The attached class expects to find Apache ExceptionUtil on the
classpath, as well as Hibernate Validation. It's easy to chop out the
hibernate validator bits if you don't use it.
--
Craig Ringer
Attachment | Content-Type | Size |
---|---|---|
DbExceptionUtil.java | text/x-java | 5.3 KB |