在我的java try - catch子句中,我希望能够捕获sql异常的确切原因(我正在使用Postgres,但这个问题适用于所有jdbc驱动程序)。我必须做的是
} 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异常?
答案 0 :(得分:0)
来自oracle docs:http://docs.oracle.com/javase/tutorial/jdbc/basics/sqlexception.html
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();
}
}
}
}
}