Search in sources :

Example 16 with Exception

use of com.microsoft.appcenter.crashes.ingestion.models.Exception in project AppCenter-SDK-Android by Microsoft.

the class Crashes method processSingleMinidump.

/**
 * Process the minidump, save an error log with a reference to the minidump, move the minidump file to the 'pending' folder.
 *
 * @param minidumpFile   a file where an ndk crash is saved.
 * @param minidumpFolder a folder that contains device info and a minidump file.
 */
private void processSingleMinidump(File minidumpFile, File minidumpFolder) {
    /* Create missing files from the native crash that we detected. */
    AppCenterLog.debug(LOG_TAG, "Process pending minidump file: " + minidumpFile);
    long minidumpDate = minidumpFile.lastModified();
    File dest = new File(ErrorLogHelper.getPendingMinidumpDirectory(), minidumpFile.getName());
    Exception modelException = new Exception();
    modelException.setType("minidump");
    modelException.setWrapperSdkName(WRAPPER_SDK_NAME_NDK);
    modelException.setMinidumpFilePath(dest.getPath());
    ManagedErrorLog errorLog = new ManagedErrorLog();
    errorLog.setException(modelException);
    errorLog.setTimestamp(new Date(minidumpDate));
    errorLog.setFatal(true);
    errorLog.setId(ErrorLogHelper.parseLogFolderUuid(minidumpFolder));
    /* Lookup app launch timestamp in session history. */
    SessionContext.SessionInfo session = SessionContext.getInstance().getSessionAt(minidumpDate);
    if (session != null && session.getAppLaunchTimestamp() <= minidumpDate) {
        errorLog.setAppLaunchTimestamp(new Date(session.getAppLaunchTimestamp()));
    } else {
        /*
             * Fall back to log date if app launch timestamp information lost
             * or in the future compared to crash time.
             * This also covers the case where app launches then crashes within 1s:
             * app launch timestamp would have ms accuracy while minidump file is without
             * ms, in that case we also falls back to log timestamp
             * (this would be same result as truncating ms).
             */
        errorLog.setAppLaunchTimestamp(errorLog.getTimestamp());
    }
    /*
         * TODO The following properties are placeholders because fields are required.
         * They should be removed from schema as not used by server.
         */
    errorLog.setProcessId(0);
    errorLog.setProcessName("");
    try {
        String savedUserId = ErrorLogHelper.getStoredUserInfo(minidumpFolder);
        Device savedDeviceInfo = ErrorLogHelper.getStoredDeviceInfo(minidumpFolder);
        if (savedDeviceInfo == null) {
            /*
                 * Fallback to use device info from the current launch.
                 * It may lead to an incorrect app version being reported.
                 */
            savedDeviceInfo = getDeviceInfo(mContext);
            savedDeviceInfo.setWrapperSdkName(WRAPPER_SDK_NAME_NDK);
        }
        errorLog.setDevice(savedDeviceInfo);
        errorLog.setUserId(savedUserId);
        saveErrorLogFiles(new NativeException(), errorLog);
        if (!minidumpFile.renameTo(dest)) {
            throw new IOException("Failed to move file");
        }
    } catch (java.lang.Exception e) {
        // noinspection ResultOfMethodCallIgnored
        minidumpFile.delete();
        removeAllStoredErrorLogFiles(errorLog.getId());
        AppCenterLog.error(LOG_TAG, "Failed to process new minidump file: " + minidumpFile, e);
    }
}
Also used : Device(com.microsoft.appcenter.ingestion.models.Device) Log.getStackTraceString(android.util.Log.getStackTraceString) IOException(java.io.IOException) Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) JSONException(org.json.JSONException) NativeException(com.microsoft.appcenter.crashes.model.NativeException) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) IOException(java.io.IOException) Date(java.util.Date) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) SessionContext(com.microsoft.appcenter.utils.context.SessionContext) File(java.io.File) NativeException(com.microsoft.appcenter.crashes.model.NativeException)

Example 17 with Exception

use of com.microsoft.appcenter.crashes.ingestion.models.Exception in project AppCenter-SDK-Android by Microsoft.

the class ErrorLogHelperTest method truncateCauses.

@Test
public void truncateCauses() {
    RuntimeException e = new RuntimeException();
    for (int i = 0; i < 32; i++) {
        e = new RuntimeException(Integer.valueOf(i).toString(), e);
    }
    int depth = 1;
    Exception model = ErrorLogHelper.getModelExceptionFromThrowable(e);
    while (model.getInnerExceptions() != null && (model = model.getInnerExceptions().get(0)) != null) {
        depth++;
    }
    assertEquals(ErrorLogHelper.CAUSE_LIMIT, depth);
}
Also used : Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) JSONException(org.json.JSONException) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) IOException(java.io.IOException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with Exception

use of com.microsoft.appcenter.crashes.ingestion.models.Exception in project AppCenter-SDK-Android by Microsoft.

the class ErrorLogHelperTest method createErrorLog.

@Test
public void createErrorLog() throws java.lang.Exception {
    /* Dummy coverage of utils class. */
    new ErrorLogHelper();
    /* Mock base. */
    Context mockContext = mock(Context.class);
    when(Process.myPid()).thenReturn(123);
    Date logTimestamp = new Date(1000L);
    whenNew(Date.class).withNoArguments().thenReturn(logTimestamp);
    whenNew(Date.class).withArguments(anyLong()).thenAnswer(new Answer<Date>() {

        @Override
        public Date answer(InvocationOnMock invocation) {
            return new Date((Long) invocation.getArguments()[0]);
        }
    });
    /* Mock device. */
    Device mockDevice = mock(Device.class);
    when(DeviceInfoHelper.getDeviceInfo(any(Context.class))).thenReturn(mockDevice);
    /* Mock process name. */
    ActivityManager activityManager = mock(ActivityManager.class);
    RunningAppProcessInfo runningAppProcessInfo = new RunningAppProcessInfo(null, 0, null);
    runningAppProcessInfo.pid = 123;
    runningAppProcessInfo.processName = "right.process";
    when(mockContext.getSystemService(Context.ACTIVITY_SERVICE)).thenReturn(activityManager);
    when(activityManager.getRunningAppProcesses()).thenReturn(Arrays.asList(mock(RunningAppProcessInfo.class), runningAppProcessInfo));
    /* Mock architecture. */
    TestUtils.setInternalState(Build.VERSION.class, "SDK_INT", 23);
    TestUtils.setInternalState(Build.class, "SUPPORTED_ABIS", new String[] { "armeabi-v7a", "arm" });
    /* Test. */
    long launchTimeStamp = 2000;
    ManagedErrorLog errorLog = ErrorLogHelper.createErrorLog(mockContext, java.lang.Thread.currentThread(), new RuntimeException(new IOException(new TestCrashException())), java.lang.Thread.getAllStackTraces(), launchTimeStamp);
    assertNotNull(errorLog);
    assertNotNull(errorLog.getId());
    assertEquals(logTimestamp, errorLog.getTimestamp());
    assertEquals(mockDevice, errorLog.getDevice());
    assertEquals(Integer.valueOf(123), errorLog.getProcessId());
    assertEquals("right.process", errorLog.getProcessName());
    assertNull(errorLog.getParentProcessId());
    assertNull(errorLog.getParentProcessName());
    assertEquals("armeabi-v7a", errorLog.getArchitecture());
    assertEquals((Long) java.lang.Thread.currentThread().getId(), errorLog.getErrorThreadId());
    assertEquals(java.lang.Thread.currentThread().getName(), errorLog.getErrorThreadName());
    assertEquals(Boolean.TRUE, errorLog.getFatal());
    assertEquals(launchTimeStamp, errorLog.getAppLaunchTimestamp().getTime());
    /* Check first exception. */
    Exception topException = errorLog.getException();
    sanityCheck(topException);
    assertEquals(RuntimeException.class.getName(), topException.getType());
    assertNotNull(topException.getMessage());
    assertNotNull(topException.getInnerExceptions());
    assertEquals(1, topException.getInnerExceptions().size());
    /* Check second exception. */
    Exception middleException = topException.getInnerExceptions().get(0);
    sanityCheck(middleException);
    assertEquals(IOException.class.getName(), middleException.getType());
    assertNotNull(middleException.getInnerExceptions());
    assertEquals(1, middleException.getInnerExceptions().size());
    /* Check third exception. */
    Exception rootCauseException = middleException.getInnerExceptions().get(0);
    sanityCheck(rootCauseException);
    assertEquals(TestCrashException.class.getName(), rootCauseException.getType());
    assertNotNull(rootCauseException.getMessage());
    assertNull(rootCauseException.getInnerExceptions());
    /* Check threads. */
    assertNotNull(errorLog.getThreads());
    assertEquals(java.lang.Thread.getAllStackTraces().size(), errorLog.getThreads().size());
    for (Thread thread : errorLog.getThreads()) {
        assertNotNull(thread);
        assertTrue(thread.getId() > 0);
        assertNotNull(thread.getName());
        assertNotNull(thread.getFrames());
        for (StackFrame frame : thread.getFrames()) {
            assertNotNull(frame);
            assertNotNull(frame.getClassName());
            assertNotNull(frame.getMethodName());
        }
    }
}
Also used : Context(android.content.Context) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) Device(com.microsoft.appcenter.ingestion.models.Device) IOException(java.io.IOException) ActivityManager(android.app.ActivityManager) Date(java.util.Date) Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) JSONException(org.json.JSONException) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) IOException(java.io.IOException) Thread(com.microsoft.appcenter.crashes.ingestion.models.Thread) RunningAppProcessInfo(android.app.ActivityManager.RunningAppProcessInfo) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Build(android.os.Build) StackFrame(com.microsoft.appcenter.crashes.ingestion.models.StackFrame) Matchers.anyLong(org.mockito.Matchers.anyLong) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 19 with Exception

use of com.microsoft.appcenter.crashes.ingestion.models.Exception in project AppCenter-SDK-Android by Microsoft.

the class ErrorLogHelper method getModelExceptionFromThrowable.

@NonNull
public static Exception getModelExceptionFromThrowable(@NonNull Throwable t) {
    Exception topException = null;
    Exception parentException = null;
    List<Throwable> causeChain = new LinkedList<>();
    for (Throwable cause = t; cause != null; cause = cause.getCause()) {
        causeChain.add(cause);
    }
    if (causeChain.size() > CAUSE_LIMIT) {
        AppCenterLog.warn(Crashes.LOG_TAG, "Crash causes truncated from " + causeChain.size() + " to " + CAUSE_LIMIT + " causes.");
        causeChain.subList(CAUSE_LIMIT_HALF, causeChain.size() - CAUSE_LIMIT_HALF).clear();
    }
    for (Throwable cause : causeChain) {
        Exception exception = new Exception();
        exception.setType(cause.getClass().getName());
        exception.setMessage(cause.getMessage());
        exception.setFrames(getModelFramesFromStackTrace(cause));
        if (topException == null) {
            topException = exception;
        } else {
            parentException.setInnerExceptions(Collections.singletonList(exception));
        }
        parentException = exception;
    }
    // noinspection ConstantConditions
    return topException;
}
Also used : Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) JSONException(org.json.JSONException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) NonNull(androidx.annotation.NonNull)

Example 20 with Exception

use of com.microsoft.appcenter.crashes.ingestion.models.Exception in project appcenter-sdk-android by microsoft.

the class HandledErrorTest method trackExceptionForWrapperSdk.

@Test
public void trackExceptionForWrapperSdk() {
    StackFrame frame = new StackFrame();
    frame.setClassName("1");
    frame.setFileName("2");
    frame.setLineNumber(3);
    frame.setMethodName("4");
    final com.microsoft.appcenter.crashes.ingestion.models.Exception exception = new com.microsoft.appcenter.crashes.ingestion.models.Exception();
    exception.setType("5");
    exception.setMessage("6");
    exception.setFrames(singletonList(frame));
    mCrashes = Crashes.getInstance();
    mChannel = mock(Channel.class);
    WrapperSdkExceptionManager.trackException(exception, null, null);
    verify(mChannel, never()).enqueue(any(Log.class), eq(mCrashes.getGroupName()), anyInt());
    mCrashes.onStarting(mAppCenterHandler);
    mCrashes.onStarted(mock(Context.class), mChannel, "", null, true);
    WrapperSdkExceptionManager.trackException(exception, null, null);
    verify(mChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && exception.equals(((HandledErrorLog) item).getException());
        }
    }), eq(mCrashes.getGroupName()), eq(DEFAULTS));
    reset(mChannel);
    WrapperSdkExceptionManager.trackException(exception, new HashMap<String, String>() {

        {
            put(null, null);
            put("", null);
            put(generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH + 1, '*'), null);
            put("1", null);
        }
    }, null);
    verify(mChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && exception.equals(((HandledErrorLog) item).getException()) && ((HandledErrorLog) item).getProperties().size() == 0;
        }
    }), eq(mCrashes.getGroupName()), eq(DEFAULTS));
    reset(mChannel);
    WrapperSdkExceptionManager.trackException(exception, new HashMap<String, String>() {

        {
            for (int i = 0; i < 30; i++) {
                put("valid" + i, "valid");
            }
        }
    }, null);
    verify(mChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && exception.equals(((HandledErrorLog) item).getException()) && ((HandledErrorLog) item).getProperties().size() == 20;
        }
    }), eq(mCrashes.getGroupName()), eq(DEFAULTS));
    reset(mChannel);
    final String longerMapItem = generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH + 1, '*');
    WrapperSdkExceptionManager.trackException(exception, new HashMap<String, String>() {

        {
            put(longerMapItem, longerMapItem);
        }
    }, null);
    verify(mChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            if (item instanceof HandledErrorLog) {
                HandledErrorLog errorLog = (HandledErrorLog) item;
                if (exception.equals((errorLog.getException()))) {
                    if (errorLog.getProperties().size() == 1) {
                        Map.Entry<String, String> entry = errorLog.getProperties().entrySet().iterator().next();
                        return entry.getKey().length() == ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH && entry.getValue().length() == ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH;
                    }
                }
            }
            return false;
        }
    }), eq(mCrashes.getGroupName()), eq(DEFAULTS));
}
Also used : Context(android.content.Context) UserIdContext(com.microsoft.appcenter.utils.context.UserIdContext) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) ErrorAttachmentLog(com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog) HandledErrorLog(com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog) Log(com.microsoft.appcenter.ingestion.models.Log) Channel(com.microsoft.appcenter.channel.Channel) HandledErrorLog(com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog) Matchers.anyString(org.mockito.Matchers.anyString) TestUtils.generateString(com.microsoft.appcenter.test.TestUtils.generateString) Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) StackFrame(com.microsoft.appcenter.crashes.ingestion.models.StackFrame) ArgumentMatcher(org.mockito.ArgumentMatcher) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Aggregations

Exception (com.microsoft.appcenter.crashes.ingestion.models.Exception)49 Test (org.junit.Test)41 IOException (java.io.IOException)38 JSONException (org.json.JSONException)38 Matchers.anyString (org.mockito.Matchers.anyString)33 ManagedErrorLog (com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)30 Log.getStackTraceString (android.util.Log.getStackTraceString)27 LogSerializer (com.microsoft.appcenter.ingestion.models.json.LogSerializer)24 File (java.io.File)23 Log (com.microsoft.appcenter.ingestion.models.Log)12 AppCenterLog (com.microsoft.appcenter.utils.AppCenterLog)12 ArgumentMatcher (org.mockito.ArgumentMatcher)12 TestCrashException (com.microsoft.appcenter.crashes.model.TestCrashException)11 ErrorAttachmentLog (com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog)9 HandledErrorLog (com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog)9 TestUtils.generateString (com.microsoft.appcenter.test.TestUtils.generateString)9 Date (java.util.Date)8 Context (android.content.Context)6 StackFrame (com.microsoft.appcenter.crashes.ingestion.models.StackFrame)6