How to handle a PSQLException in java?

后端 未结 4 944
孤街浪徒
孤街浪徒 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:32

    This is quite late, but building on previous responses I was able to solve it as so:

    try {
        return this.projectRepository.saveAndFlush(patchedProjectEntity);
    } catch (DataIntegrityViolationException e) {
        if (e.getMostSpecificCause().getClass().getName().equals("org.postgresql.util.PSQLException") && ((SQLException) e.getMostSpecificCause()).getSQLState().equals("23505"))
            throw new UniqueConstraintViolationException("", e.getMostSpecificCause());
        throw e;
    }
    

    Where UniqueConstraintViolationException is a custom exception and handled with a spring controller advice.

提交回复
热议问题