【问题标题】:proper way to capture meaningful sql exception捕获有意义的 sql 异常的正确方法
【发布时间】:2014-04-30 07:34:12
【问题描述】:

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

【问题讨论】:

  • 这个问题没有被标记为 java 有什么原因吗?
  • 是的,使用 SQLException 确实“非常糟糕”。 Apache ExceptionUtils 有点帮助。一般来说,您应该尽可能地依赖 SQLState,而不是使用异常类匹配。

标签: java sql postgresql exception jdbc


【解决方案1】:

来自 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();
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2011-07-28
    • 2018-07-28
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多