ピットシリーズ(7)UnknownHostExceptionはprintlns印刷をサポートしていません


げんしょう


今日のテストでは、ネットワークがない場合、try catch内でLogを呼び出すと、次の方法で異常情報が印刷され、出力されないことがわかりました.同様にローカルファイルへの書き込みに成功しなかったのはおかしい.
    public static int e(String tag, String msg, Throwable tr) {
        return printlns(LOG_ID_MAIN, ERROR, tag, msg, tr);
    }

ぶんせき


その後、ソースコードを見ると、UnknownHostException異常に対して特別な制限がなされていることがわかりました.情報セキュリティの面から、この異常な情報を印刷出力しない可能性があります.コードを見てみましょう.
    if (tr != null) {
        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                break;
            }
            if (t instanceof DeadSystemException) {
                lbbw.println("DeadSystemException: The system died; "
                        + "earlier logs will point to the root cause");
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            tr.printStackTrace(lbbw);
        }
    }

なぜローカルファイルも書き込みに成功しなかったのでしょうか.これは、書き込み時にgetStackTraceStringメソッドを呼び出して異常追跡情報を取得し、同様にシステムもこのメソッドを制限したためです.
        Throwable trace = current.getTrace();
        if (trace != null) {
            // todo:  UnknownHostException
            msg = Log.getStackTraceString(trace);
        }

ソースコードを見ると、変な知識がまた増えた.そこで、UnknownHostExceptionに対してe.toString()を出力することで、この問題を回避することができます.
    public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new FastPrintWriter(sw, false, 256);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }