Java 捕获有意义sql异常的正确方法
在我的Javatry-catch子句中,我希望能够捕获sql异常的确切原因(我使用的是Postgres,但这个问题适用于所有jdbc驱动程序)。我要做的是Java 捕获有意义sql异常的正确方法,java,sql,postgresql,exception,jdbc,Java,Sql,Postgresql,Exception,Jdbc,在我的Javatry-catch子句中,我希望能够捕获sql异常的确切原因(我使用的是Postgres,但这个问题适用于所有jdbc驱动程序)。我要做的是 } catch (Throwable ex) { // Rollback only ex.printStackTrace(); String message = ex.getMessage(); Throwable cause = ex.getCause(); i
} catch (Throwable ex) {
// Rollback only
ex.printStackTrace();
String message = ex.getMessage();
Throwable cause = ex.getCause();
if (cause instanceof ConstraintViolationException){
SQLException exc = ((ConstraintViolationException)cause).getSQLException();
if (exc instanceof BatchUpdateException){
SQLException nextEx = ((BatchUpdateException)exc).getNextException();
if (nextEx instanceof PSQLException){
message = ((PSQLException)nextEx).getMessage();
}
}
}
throw new RecordServiceException(message);
}
这太糟糕了,只适用于非常特定的异常类型。是否有一种更普遍有效的方法来捕获有意义的sql异常?来自oracle文档:
这个问题没有标记为java有什么原因吗?是的,使用SQLException确实“非常糟糕”。有点帮助。通常,您应该尽可能地依赖SQLState,而不是使用异常类匹配。
public static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
if (ignoreSQLException(
((SQLException)e).
getSQLState()) == false) {
e.printStackTrace(System.err);
System.err.println("SQLState: " +
((SQLException)e).getSQLState());
System.err.println("Error Code: " +
((SQLException)e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while(t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}