jOOQ: DataAccessException and constraints
Asked Answered
M

2

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.

Mauser answered 23/2, 2015 at 13:13 Comment(4)
you can call e.getCause() on the JOOQ exception to drill down.Yurik
@Yurik That returns only a PSQLException without further distinction.Mauser
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?Decommission
I will take a look to Spring's translation!Mauser
M
3

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

Mauser answered 24/2, 2015 at 16:43 Comment(0)
Q
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 ");
    }
    }
Quipu answered 8/5, 2020 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.