2016-10-28 87 views
1

我對我的一個實體有一個唯一的約束,並且每當我違反約束時發生PSQLException時,我都會迴應一個錯誤的請求。如何在java中處理PSQLException?

這就是我想實現我的異常處理程序:

@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")) { 
// 
//  } 
    } 

} 

而這正是該模型被保存在數據庫:

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 ?*/ 
      } 
} 

這是當我補充一點,被拋出的異常重複條目:

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] 

如何處理PSQLExceptions?我是否應該將自己的例外作爲包裝或如何解決這個問題?

+0

處理它正好趕上'SQLException' –

+0

究竟你的意思是什麼「處理」?你想在功能上實現什麼? – Gimby

+1

與SQLException一樣,它表示它永遠不會從相應的塊中拋出。當用戶嘗試在DB中輸入重複值時,我嘗試使用BAD_REQUEST狀態碼進行響應。 – Gustavo

回答

1

您正在捕捉PSQLException。取而代之的是,請抓住SQLException。使用SQLException,您可以處理所有這些SQL異常。

您可以在this link

然後在你的代碼只是把SQLException中,只要你想檢查的SQLException知識。最通用的catch子句如下:

catch (SQLException e) 
    { 
    System.out.println("ERROR: Fetch statement failed: " + 
     e.getMessage()); 
    } 

使用此代碼,您正在打印該例外。如果你想了解更多信息,請查看this

2

關鍵問題是PSQLException被封裝成一些Spring異常(我從你的代碼中假設);你要解開它(例如使用番石榴的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 :) 
       } 
      } 
     } 
    } 
} 

一旦你這樣做,你可以把你的自定義異常,並在DatabaseExceptionHandler