2016-10-28 76 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