我对我的一个实体有一个唯一的约束,并且每当我违反约束时发生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