Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 捕获有意义sql异常的正确方法_Java_Sql_Postgresql_Exception_Jdbc - Fatal编程技术网

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

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

在我的Javatry-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文档:


这个问题没有标记为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();
                }
            }
        }
    }
}