Using JOOQ, how do you map SQLException to a business exception?

I am using JOOQ and want to map specific SQLExceptions to business exceptions. On the exception handling documentation page it says:

In the next section on the listener executor docs, there is an option to override jOOQ's exception handling if you want to deal with some types of constraint violations or if you are making business mistakes from your database, etc.

However, there are no practical examples on the page about execution listeners.

I know I need to implement a method ExecuteListener

exception(ExecuteContext)

, but it is not clear to me if I should have throw

another exception, or if I should instead use a method ExecuteContext.exception

to override the existing exception. For example.

@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()));
    }
}

      

+3


source to share


1 answer


I'm afraid you'll have to do it yourself. That's why...

Using ExecuteListener won't work for you

The route of choice ExecuteListener

for automatic and global translation a SQLException

is useful if you want alternative exceptions for jOOQ DataAccessException

- like Spring DataAccessException

for further processing ( translation example here ). It is not suitable for automatically resetting a constraint exclusion for a particular "business exception" because ExecuteListener

(as a global entity) it does not know in what context a constraint violation might have occurred. May be:

  • Errors causing constraint violations (for example, you must update, not insert)
  • User errors causing constraint violations (for example, the user submitted the form twice)
  • Actual business rules causing constraint violations (such as validation)

You have to decide this on a case-by-case basis, I'm afraid. ExecuteListener

will only help you redo the technical part of exception handling.



Why does the manual mention "business mistakes"?

You pointed out the manual:

or if you are making business mistakes from your database

These business errors can be user-defined errors that you raise from a database trigger, for example, in case you don't get a constraint violation but a meaningful business error directly from the database.

+2


source







All Articles