我對我的一個實體有一個唯一的約束,並且每當我違反約束時發生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?我是否應該將自己的例外作爲包裝或如何解決這個問題?
處理它正好趕上'SQLException' –
究竟你的意思是什麼「處理」?你想在功能上實現什麼? – Gimby
與SQLException一樣,它表示它永遠不會從相應的塊中拋出。當用戶嘗試在DB中輸入重複值時,我嘗試使用BAD_REQUEST狀態碼進行響應。 – Gustavo