title: How to handle a PSQLException in java?
body: <p>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.</p>
  
  <p>This is my exception handler which I tried to implement:</p>
  
  <pre><code>@ControllerAdvice
  public class DatabaseExceptionHandler {
      @ExceptionHandler(value = PSQLException.class)
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      public void handleDatabaseExceptions(PSQLException e) {
          // i want to respond with a bad request only when this condition is satisfied
  //
  //        if (e.getSQLState().equals("23505")) {
  //
  //        }
      }
  
  }
  </code></pre>
  
  <p>And this is where the model is saved in db:</p>
  
  <pre><code> public DepartmentForHoliday setDepartment(DepartmentForHoliday department) {
          if (department.getDepartmentId() == null) {
              Department savedDepartment = new Department();
              savedDepartment.setName(department.getName());
              try {
                  departmentRepository.save(savedDepartment);
              } catch (PSQLException e) {
                /*here i have a compiler error which says that this exception is never thrown in the corresponding try block, but where ?*/
              }
  }
  </code></pre>
  
  <p>This is the exception that is thrown when I add a duplicate entry:</p>
  
  <pre><code>org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_1t68827l97cwyxo9r1u6t4p7d"
    Detail: Key (name)=(Tech) already exists.
      at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2458) ~[postgresql-9.4.1211.jre7.jar:9.4.1211.jre7]
  </code></pre>
  
  <p>How to handle PSQLExceptions ? Should I make my own exception as a wrapper or how to solve this problem ?</p>