e.printStackTrace(); in string

前端 未结 5 1278
执笔经年
执笔经年 2021-01-30 13:00

There are e.printStackTrace() method to print exceptional error, so I would like to take entire exception in String and show it by Toast.makeText

相关标签:
5条回答
  • 2021-01-30 13:22
    import android.util.Log;
    
    ...
    
    String stackTrace = Log.getStackTraceString(e);
    
    0 讨论(0)
  • 2021-01-30 13:28

    Use the following piece of code:

    Writer writer = new StringWriter();
    exception.printStackTrace(new PrintWriter(writer));
    String s = writer.toString();
    

    There used to be a way to extract an exception stacktrace into the String in one line with Log.getStackTraceString call. But starting from Android 4.0 (API 14) that method is not reliable anymore, as it returns an empty string for UnknownHostException (see Android issue #21436 for the details, in short: "to reduce the amount of log spew that apps do in the non-error condition of the network being unavailable" Android engineers made IMHO a dubious decision to modify Log.getStackTraceString method).

    Thus it is better to use the code I provided at the beginning of this post.

    0 讨论(0)
  • 2021-01-30 13:32

    It's doable, but don't do this. Show just the error message (even that is too much for 'real' users), the full stack trace should go to the log only.

    0 讨论(0)
  • 2021-01-30 13:36

    In your exception handler use:

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    
    e.printStackTrace(pw);
    
    whateverFunctionYouLikeToPrintYourStackTrace(sw.getBuffer().toString());
    

    However, you're much better off using ADB with logcat, because stack traces on Toasts look terrible.

    0 讨论(0)
  • 2021-01-30 13:40

    you can print the stack trace to a stream & read from it.

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(baos);
    
    e.printStackTrace(pw);
    String stachTrace = new String(baos.toByteArray());
    

    or you can use a StringWriter in place of the ByteArrayOutputStream.

    0 讨论(0)
提交回复
热议问题