gpt4 book ai didi

java - 捕获有意义的 sql 异常的正确方法

转载 作者:行者123 更新时间:2023-11-29 13:59:54 26 4
gpt4 key购买 nike

在我的 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 异常?

最佳答案

来自 Oracle 文档: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();
}
}
}
}
}

关于java - 捕获有意义的 sql 异常的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com