How to handle a PSQLException in java?

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

    You might as well register an exception handler for that wrapped exception (that @radek mentioned) directly.

    In your case that's:

    @ExceptionHandler(DataIntegrityViolationException::class)
    protected fun handleDataIntegrityException(ex: DataIntegrityViolationException, request: WebRequest) : ResponseEntity{
        return ResponseEntity.badRequest().body(someBodyHere)
    }
    

    The error is converted within convertHibernateAccessException in org.springframework.orm.jpa.vendorHibernateJpaDialect, which has already processed away from PSQL. You can add a breakpoint there and follow the stacktrace.

    There is a lot of proxy'ing happening under the hood, but the takeaway is that there is always a readable, expressive Exception to use directly.

提交回复
热议问题