Java - find the first cause of an exception

后端 未结 10 993
渐次进展
渐次进展 2020-12-09 01:50

I need to check if an exception is caused by some database problem. I receive an Exception and check if its cause contains the \"ORA\" string and return that (something like

10条回答
  •  时光取名叫无心
    2020-12-09 02:13

    You could improve your code checking for SQLException

    import java.sql.SQLException;
    
    private static final String ORACLE = "ORA";
    
    public String doHandle(Throwable t) {
        if (t.getClass().isAssignableFrom(SQLException.class)) {
        SQLException e = (SQLException) t;
        int errCode = e.getErrorCode();
        String state = e.getSQLState();
        String msg = e.getMessage();
        if (msg.contains(ORACLE)) {
            return msg;
            }
        } else {
            if (t.getCause() != null) {
                return this.doHandle(t.getCause());
                }
            }
        return "";
    }
    

    Also, I think in Oracle "errCode" contains the number associated to ORA-nnnn

提交回复
热议问题