Reputation: 33
I'm Using JOOQ, and would like to map certain SQLExceptions to business exceptions. The exception handling documentation page says:
The following section about execute listeners documents means of overriding jOOQ's exception handling, if you wish to deal separately with some types of constraint violations, or if you raise business errors from your database, etc.
However, on the page about execute listeners has no practical examples.
I know I have to implement ExecuteListener
's method exception(ExecuteContext)
, but it's unclear to me whether I should throw
another exception from there, or instead use the ExecuteContext.exception
method to override the existing exception. Eg.
@Override
public void exception(ExecuteContext ctx) {
if (ctx.sqlException().getSQLState().equals("23503")) {
throw new ForeignKeyViolationException("Foreign key violation", ctx.sqlException());
}
}
Or:
@Override
public void exception(ExecuteContext ctx) {
if (ctx.sqlException().getSQLState().equals("23503")) {
ctx.exception(ForeignKeyViolationException("Foreign key violation", ctx.sqlException()));
}
}
Upvotes: 3
Views: 1581
Reputation: 221145
I'm afraid, you'll have to do the work yourself. Here's why...
The route of choosing an ExecuteListener
for automatic and global translation of a SQLException
is useful if you want alternative exceptions to jOOQ's DataAccessException
- e.g. Spring's DataAccessException
for further processing (example translator here). It is not suitable for automatically rewiring a constraint violation exception to a specific "business exception", because the ExecuteListener
(as a global actor) doesn't know in what context a constraint violation may have happened. There could be:
You have to decide this for each query individually, I'm afraid. ExecuteListener
only helps you rewire the technical part of exception handling.
You've quoted the manual:
or if you raise business errors from your database
These business errors might be user-defined errors that you raise from a database trigger, for instance, in case of which you won't be getting a constraint violation, but a meaningful business error directly from the database.
Upvotes: 3