8

I am implementing a REST API with Jersey and jOOQ.

I have a table with some constraints, for example a unique key. When inserting a tuple which violates this constraint, jOOQ throws a DataAccessException:

org.jooq.exception.DataAccessException: SQL [insert into ...]; ERROR: duplicate key value violates unique constraint "issue_name_key"

Is there a way to find out which constraint has been violated, without string-parsing the error message? If a constraint is violated, I want to return a 400 bad request http status code instead of a 500 general error.

If this is not possible, what is common practise here? Should I query the database for each possible constraint violation? This smells like a maintenance trap.

  • you can call `e.getCause()` on the JOOQ exception to drill down. – assylias Feb 23 '15 at 13:22
  • @assylias That returns only a `PSQLException` without further distinction. –  Feb 23 '15 at 13:27
  • jOOQ doesn't have anything built in to disambiguate such exceptions - e.g. when JDBC drivers don't make use of all the possible JDBC exceptions. But perhaps, you could use Spring's exception translation mechanism for this? – Lukas Eder Feb 23 '15 at 16:53
  • I will take a look to Spring's translation! –  Feb 24 '15 at 16:42

2 Answers2

3

As per comment by Lukas Eder: not possible in jOOQ, since it only relies on JDBC exceptions.

0

I am not sure jOOQ DataAccessException supports the 'contains' method .But with "org.springframework.dao.DataAccessException" , we can implement in the following way.

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;

    catch(DataAccessException sqlExcep) {
                if(sqlExcep.contains(DuplicateKeyException.class)) {
    System.out.println("Duplicate key exception found. Return 400 bad request ");
    }
    else {
    System.out.println("Some other  exception. Return 500 bad request ");
    }
    }
premSiva
  • 111
  • 1
  • 5