How to get information about error from SqlExceptionHelper for REST spring application

Viewed 1019

I have some tables in my database and I want to get information about wrong requests to the database. In case If I'm trying to save entity with wrong foreigns keys, I want to get detail information about these keys.

For example:

2020-03-25 18:37:37.595 ERROR 9788 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: insert or update on table "student" violates foreign key constraint "student_fkey_to_specialty"
  Detail: Key (specialtykey)=(2) is not present in table "specialty".

I tried to solve with this code, but I get other information.

could not execute statement; SQL [n/a]; constraint [student_fkey_to_specialty]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

my code:

@PostMapping
    public void saveStudent(@RequestBody StudentDTO studentDTO) {
        if(studentDTO!=null){
            try {
                studentService.save(studentDTO);

            }catch (Exception|Error e){
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getLocalizedMessage(),e );
            }
        }
    }
3 Answers

Use a loop to iterate to the original exception, here a example function that does that:

private String getCauseMessage(Throwable t)

    Throwable cause = t;
    while (t.getCause() != null) {
        cause = t.getCause();
    }

    return t.getLocalizedMessage();
}

As you never know how many exception might be chained together, using a loop is the safest way. If you just use it directly you risk getting a NullPointerException or not getting the message of the original exception.

Student table is having "student_fkey_to_specialty" which is getting violated. Check on which filed this constraint is and provide the correct value for that field

I solved this problem with this code. This allows getting information about exceptions from the database.

e.getCause().getCause().getLocalizedMessage()
Related