How to handle a PSQLException in java?

后端 未结 4 932
孤街浪徒
孤街浪徒 2021-02-09 08:43

I have a unique constraint on one of my entities and whenever I get a PSQLException which occurs whenever that constraint is violated, I want to respond with a bad request.

4条回答
  •  既然无缘
    2021-02-09 09:23

    Key problem is that PSQLException is wrapped into some Spring exception (which I assume from your code); you have to unwrap it (for example using guava's Throwables):

    public DepartmentForHoliday setDepartment(DepartmentForHoliday department) {
        if (department.getDepartmentId() == null) {
            Department savedDepartment = new Department();
            savedDepartment.setName(department.getName());
            try {
                departmentRepository.save(savedDepartment);
            } catch (RuntimeException e) {
                Throwable rootCause = com.google.common.base.Throwables.getRootCause(e);
                if (rootCause instanceof SQLException) {
                    if ("23505".equals(((SQLException) rootCause).getSQLState())) {
                        // do smth interesting :)
                    }
                }
            }
        }
    }
    

    Once you do that you can throw your custom exception and handle it in DatabaseExceptionHandler

提交回复
热议问题