mar*_*mor 3 java android try-catch stack-trace crashlytics
我有一个实用方法来计时和记录整个项目中的各种查询。问题是,crashlytics现在看来,所有不相关的崩溃都被合并到一个崩溃实例中。
我可以捕获实用程序方法上的所有异常,并在从堆栈中删除该方法后抛出它们吗?
环境是Android(Java)
更新:
根据下面@Dhananjay 的回答,这是我的代码:
public static Cursor get(...) {
try {
// my utility code
} catch (RuntimeException e) {
throw cleanException(e);
}
}
private static RuntimeException cleanException(RuntimeException e) {
try {
StackTraceElement[] stackTrace = e.getStackTrace();
StackTraceElement[] subTrace = new StackTraceElement[stackTrace.length - 1];
System.arraycopy(stackTrace, 1, subTrace, 0, subTrace.length);
e.setStackTrace(subTrace);
return e;
} catch (Throwable ignored) {
return e;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这种方法可能会解决您的问题:在实用程序日志记录方法中设置异常的堆栈跟踪以排除实用程序方法本身,然后抛出异常,这是一个工作示例,您可以修改它以消除您想要的任何异常StackTraceElement:
package test;
public class TestMain {
public static void main(String args[]) throws Exception {
try {
apiCall();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void apiCall() throws Exception {
logAndThrow();
}
public static void logAndThrow() throws Exception {
Exception e = new Exception();
StackTraceElement[] cleanedUpStackTrace = new StackTraceElement[e.getStackTrace().length -1];
// Eliminate this mehod i.e. logAndThrow's stack trace entry (i.e. the first one) in cleanedUpStackTrace
System.arraycopy(e.getStackTrace(), 1, cleanedUpStackTrace, 0, cleanedUpStackTrace.length);
for(StackTraceElement ste : cleanedUpStackTrace) {
System.out.println(ste.getMethodName());
}
e.setStackTrace(cleanedUpStackTrace);
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
这是该程序的输出,该logAndThrow方法现在不存在于堆栈跟踪中:
apiCall
main
java.lang.Exception
at test.TestMain.apiCall(TestMain.java:33)
at test.TestMain.main(TestMain.java:25)
Run Code Online (Sandbox Code Playgroud)