【问题标题】:How can I get an error message as a string when I can't use the debugger当我无法使用调试器时,如何以字符串形式获取错误消息
【发布时间】:2020-09-29 00:23:01
【问题描述】:

我希望能够将整个错误日志保存到 java 中的字符串。例如,如果我有这条线

int a = 0/0

然后这会在调试器中给出以下错误消息:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at HelloWorld.main(HelloWorld.java:8)

我想要的是能够将上述错误消息完全放在一个字符串中。我已经尝试在 try/catch 块中包含我想要的错误字符串(对于这个例子,除以零)的代码,如下所示,但这只会给我java.lang.ArithmeticException: / by zero 部分。

这是我的 try/catch 块:

try{
       int a = 0/0;
   }catch(Exception e){
       String a = getFullErrorString(e);
   }

我的方法是:

public static String getFullErrorString(Throwable error){        
    return(
            error.getCause() == null ? String.valueOf(error) : (error + "\n" + getFullErrorString(error.getCause()))
            );       
}

我需要这样做,因为我的应用程序不能同时使用调试器和外部设备(外部设备使用 USB-C 端口,因此我无法在插入它的情况下进行调试,而蓝牙不是一个选项,因为我的应用程序大量使用蓝牙)。请帮忙!

【问题讨论】:

  • 对于远程错误调试,您可以使用 Firebase CrashLytics
  • 将文本写入文件有用吗?
  • @NormR 我确实将它写入日志文件,但我没有在我的问题中提到这一点,因为一旦我将它作为字符串写入文件是微不足道的

标签: java android error-handling runtime-error


【解决方案1】:

这是一个我发现对捕获和记录异常有用的类:

        String rootDir = Environment.getExternalStorageDirectory().getPath();

    //----------------------------------------------------
    // Define inner class to handle exceptions
    class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
        public void uncaughtException(Thread t, Throwable e){
           java.util.Date dt =  new java.util.Date();
           String fn = rootDir + "/YourFilenameHere_" + sdf.format(dt) + "_DBG.txt";
           try{ 
              PrintStream ps = new PrintStream( fn );
              e.printStackTrace(ps);
              ps.close();
              System.out.println("wrote trace to " + fn);
              e.printStackTrace(); // capture here also???
//              SaveStdOutput.stop(); // close here vs calling flush() in class 
           }catch(Exception x){
              x.printStackTrace();
           }
           lastUEH.uncaughtException(t, e); // call last one  Gives: "Unfortunately ... stopped" message
           return;    //???? what to do here
        }
    }


    Thread.UncaughtExceptionHandler lastUEH = null;

// Then in onCreate:
        lastUEH = Thread.getDefaultUncaughtExceptionHandler();  // save previous one
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());

堆栈跟踪被写入文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多