diff --git a/app/src/main/java/com/nextcloud/client/errorhandling/ErrorReportGenerator.kt b/app/src/main/java/com/nextcloud/client/errorhandling/ErrorReportGenerator.kt new file mode 100644 index 000000000000..985ecc0b2605 --- /dev/null +++ b/app/src/main/java/com/nextcloud/client/errorhandling/ErrorReportGenerator.kt @@ -0,0 +1,99 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.nextcloud.client.errorhandling + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import com.owncloud.android.BuildConfig +import com.owncloud.android.R +import com.owncloud.android.lib.common.utils.Log_OC + +class ErrorReportGenerator( + private val context: Context, + private val supportedAbis: List = Build.SUPPORTED_ABIS.toList() +) { + + companion object { + private const val TAG = "ErrorReportGenerator" + + /** + * The report is sent to [ShowErrorActivity] as an Intent extra, which must stay well below + * the 1 MB Binder transaction limit. This value not limits to the 1MB, places somewhere reasonable + */ + const val MAX_STACK_TRACE_LENGTH = 100_000 + const val TRUNCATION_MARKER = "characters truncated" + } + + fun generate(thread: Thread, exception: Throwable): String { + val stackTrace = formatStackTrace(thread, exception) + + return """ + |### Cause of error + |```java + ${stackTrace.prependIndent("|")} + |``` + | + |### App information + |* ID: `${BuildConfig.APPLICATION_ID}` + |* Version: `${installedVersionCode()}${buildNumberSuffix()}` + |* Version name: `${BuildConfig.VERSION_NAME}` + |* Build flavor: `${BuildConfig.FLAVOR}` + | + |### Device information + |* Brand: `${Build.BRAND}` + |* Device: `${Build.DEVICE}` + |* Model: `${Build.MODEL}` + |* Id: `${Build.ID}` + |* Product: `${Build.PRODUCT}` + |* Supported ABIs: `${supportedAbis.joinToString()}` + | + |### Firmware + |* SDK: `${Build.VERSION.SDK_INT}` + |* Release: `${Build.VERSION.RELEASE}` + |* Incremental: `${Build.VERSION.INCREMENTAL}` + """.trimMargin("|") + } + + private fun formatStackTrace(thread: Thread, exception: Throwable): String { + val stackTrace = "Exception in thread \"${thread.name}\" ${exception.stackTraceToString()}".trimEnd() + if (stackTrace.length <= MAX_STACK_TRACE_LENGTH) { + return stackTrace + } + + return truncateMiddle(stackTrace) + } + + private fun truncateMiddle(stackTrace: String): String { + val keptLengthPerSide = MAX_STACK_TRACE_LENGTH / 2 + val removedLength = stackTrace.length - keptLengthPerSide * 2 + val head = stackTrace.take(keptLengthPerSide) + val tail = stackTrace.takeLast(keptLengthPerSide) + + return "$head\n... ($removedLength $TRUNCATION_MARKER) ...\n$tail" + } + + private fun buildNumberSuffix(): String { + val buildNumber = context.resources.getString(R.string.buildNumber) + if (buildNumber.isEmpty()) { + return "" + } + + return " (build #$buildNumber)" + } + + /** + * F-Droid ships one APK per ABI, each with its own versionCode, while [BuildConfig.VERSION_CODE] is + * shared by all of them. Read the installed APK's versionCode to report the right one. + */ + private fun installedVersionCode(): Long = try { + context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode + } catch (e: PackageManager.NameNotFoundException) { + Log_OC.e(TAG, "Could not read installed versionCode", e) + BuildConfig.VERSION_CODE.toLong() + } +} diff --git a/app/src/main/java/com/nextcloud/client/errorhandling/ExceptionHandler.kt b/app/src/main/java/com/nextcloud/client/errorhandling/ExceptionHandler.kt index ecb7d904869a..435c76c0c2b7 100644 --- a/app/src/main/java/com/nextcloud/client/errorhandling/ExceptionHandler.kt +++ b/app/src/main/java/com/nextcloud/client/errorhandling/ExceptionHandler.kt @@ -1,6 +1,7 @@ /* * Nextcloud - Android Client * + * SPDX-FileCopyrightText: 2026 Alper Ozturk * SPDX-FileCopyrightText: 2022 Álvaro Brey * SPDX-FileCopyrightText: 2019 Tobias Kaminsky * SPDX-FileCopyrightText: 2019 Andy Scherzinger @@ -11,92 +12,35 @@ package com.nextcloud.client.errorhandling import android.content.Context -import android.content.Intent -import android.os.Build -import com.owncloud.android.BuildConfig -import com.owncloud.android.R class ExceptionHandler( - private val context: Context, - private val defaultExceptionHandler: Thread.UncaughtExceptionHandler -) : Thread.UncaughtExceptionHandler { - - companion object { - private const val LINE_SEPARATOR = "\n" - private const val EXCEPTION_FORMAT_MAX_RECURSIVITY = 10 + context: Context, + private val defaultExceptionHandler: Thread.UncaughtExceptionHandler, + private val reportGenerator: ErrorReportGenerator = ErrorReportGenerator(context), + private val showReport: (String) -> Unit = { report -> + context.startActivity(ShowErrorActivity.createIntent(context, report)) } +) : Thread.UncaughtExceptionHandler { + @Suppress("TooGenericExceptionCaught") override fun uncaughtException(thread: Thread, exception: Throwable) { try { - val errorReport = generateErrorReport(formatException(thread, exception)) - val intent = Intent(context, ShowErrorActivity::class.java) - intent.putExtra(ShowErrorActivity.EXTRA_ERROR_TEXT, errorReport) - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK - context.startActivity(intent) - // Pass exception to OS for graceful handling - OS will report it via ADB - // and close all activities and services. - defaultExceptionHandler.uncaughtException(thread, exception) - } catch (fatalException: Exception) { - // do not recurse into custom handler if exception is thrown during - // exception handling. Pass this ultimate fatal exception to OS - defaultExceptionHandler.uncaughtException(thread, fatalException) + showReport(reportGenerator.generate(thread, exception)) + } catch (reportFailure: Throwable) { + // Keep the original crash as the one reported to the OS, so logcat and Play Console show the real cause. + addSuppressedSafely(exception, reportFailure) } - } - private fun formatException(thread: Thread, exception: Throwable): String { - fun formatExceptionRecursive(thread: Thread, exception: Throwable, count: Int = 0): String { - if (count > EXCEPTION_FORMAT_MAX_RECURSIVITY) { - return "Max number of recursive exception causes exceeded!" - } - // print exception - val stringBuilder = StringBuilder() - val stackTrace = exception.stackTrace - stringBuilder.appendLine("Exception in thread \"${thread.name}\" $exception") - // print available stacktrace - for (element in stackTrace) { - stringBuilder.appendLine(" at $element") - } - // print cause recursively - exception.cause?.let { - stringBuilder.append("Caused by: ") - stringBuilder.append(formatExceptionRecursive(thread, it, count + 1)) - } - return stringBuilder.toString() - } - - return formatExceptionRecursive(thread, exception, 0) + // Pass exception to OS for graceful handling - OS will report it via ADB + // and close all activities and services. + defaultExceptionHandler.uncaughtException(thread, exception) } - private fun generateErrorReport(stackTrace: String): String { - val buildNumber = context.resources.getString(R.string.buildNumber) - - val buildNumberString = when { - buildNumber.isNotEmpty() -> " (build #$buildNumber)" - else -> "" + private fun addSuppressedSafely(exception: Throwable, reportFailure: Throwable) { + if (reportFailure === exception) { + return } - return """ - |### Cause of error - |```java - ${stackTrace.prependIndent("|")} - |``` - | - |### App information - |* ID: `${BuildConfig.APPLICATION_ID}` - |* Version: `${BuildConfig.VERSION_CODE}$buildNumberString` - |* Build flavor: `${BuildConfig.FLAVOR}` - | - |### Device information - |* Brand: `${Build.BRAND}` - |* Device: `${Build.DEVICE}` - |* Model: `${Build.MODEL}` - |* Id: `${Build.ID}` - |* Product: `${Build.PRODUCT}` - | - |### Firmware - |* SDK: `${Build.VERSION.SDK_INT}` - |* Release: `${Build.VERSION.RELEASE}` - |* Incremental: `${Build.VERSION.INCREMENTAL}` - """.trimMargin("|") + exception.addSuppressed(reportFailure) } } diff --git a/app/src/main/java/com/nextcloud/client/errorhandling/ShowErrorActivity.kt b/app/src/main/java/com/nextcloud/client/errorhandling/ShowErrorActivity.kt index 40d17999f1f5..870297033774 100644 --- a/app/src/main/java/com/nextcloud/client/errorhandling/ShowErrorActivity.kt +++ b/app/src/main/java/com/nextcloud/client/errorhandling/ShowErrorActivity.kt @@ -1,17 +1,20 @@ /* * Nextcloud - Android Client * + * SPDX-FileCopyrightText: 2026 Alper Ozturk * SPDX-FileCopyrightText: 2019 Andy Scherzinger * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only */ package com.nextcloud.client.errorhandling +import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar +import com.nextcloud.android.common.ui.util.extensions.applyEdgeToEdgeWithSystemBarPadding import com.nextcloud.client.utils.IntentUtil import com.nextcloud.utils.SnackbarUtil import com.owncloud.android.R @@ -23,9 +26,16 @@ class ShowErrorActivity : AppCompatActivity() { companion object { const val EXTRA_ERROR_TEXT = "error" + + fun createIntent(context: Context, errorText: String): Intent = + Intent(context, ShowErrorActivity::class.java).apply { + putExtra(EXTRA_ERROR_TEXT, errorText) + flags = Intent.FLAG_ACTIVITY_NEW_TASK + } } override fun onCreate(savedInstanceState: Bundle?) { + applyEdgeToEdgeWithSystemBarPadding() super.onCreate(savedInstanceState) binding = ActivityShowErrorBinding.inflate(layoutInflater) @@ -34,7 +44,7 @@ class ShowErrorActivity : AppCompatActivity() { binding.textViewError.text = intent.getStringExtra(EXTRA_ERROR_TEXT) setSupportActionBar(binding.toolbarInclude.toolbar) - supportActionBar!!.title = createErrorTitle() + supportActionBar?.title = createErrorTitle() SnackbarUtil.create(binding.errorPageContainer, R.string.error_report_issue_text, Snackbar.LENGTH_INDEFINITE) ?.setAction(R.string.error_report_issue_action) { reportIssue() } @@ -64,10 +74,12 @@ class ShowErrorActivity : AppCompatActivity() { } private fun onClickedShare() { - val intent = Intent(Intent.ACTION_SEND) - intent.putExtra(Intent.EXTRA_SUBJECT, createErrorTitle()) - intent.putExtra(Intent.EXTRA_TEXT, binding.textViewError.text) - intent.type = "text/plain" + val intent = Intent(Intent.ACTION_SEND).apply { + putExtra(Intent.EXTRA_SUBJECT, createErrorTitle()) + putExtra(Intent.EXTRA_TEXT, binding.textViewError.text) + type = "text/plain" + } + startActivity(intent) } } diff --git a/app/src/main/res/layout/activity_show_error.xml b/app/src/main/res/layout/activity_show_error.xml index cdc077619a07..fddd6fd9f88a 100644 --- a/app/src/main/res/layout/activity_show_error.xml +++ b/app/src/main/res/layout/activity_show_error.xml @@ -12,10 +12,6 @@ - - + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.nextcloud.client.errorhandling + +import android.content.Context +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import com.owncloud.android.BuildConfig +import com.owncloud.android.R +import io.mockk.every +import io.mockk.mockk +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class ErrorReportGeneratorTest { + + companion object { + private const val PACKAGE_NAME = "com.nextcloud.client" + private const val INSTALLED_VERSION_CODE = 350200902L + private const val THREAD_NAME = "main" + private val SUPPORTED_ABIS = listOf("arm64-v8a", "armeabi-v7a") + } + + private val packageInfo = mockk() + private val packageManager = mockk() + private val context = mockk() + + private lateinit var generator: ErrorReportGenerator + + @Before + fun setUp() { + every { context.packageName } returns PACKAGE_NAME + every { context.packageManager } returns packageManager + every { context.resources.getString(R.string.buildNumber) } returns "" + every { packageManager.getPackageInfo(PACKAGE_NAME, 0) } returns packageInfo + every { packageInfo.longVersionCode } returns INSTALLED_VERSION_CODE + + generator = ErrorReportGenerator(context, SUPPORTED_ABIS) + } + + private fun generate(exception: Throwable): String = generator.generate(Thread(THREAD_NAME), exception) + + @Test + fun `print full report to test output`() { + val exception = IllegalStateException("outer", IllegalArgumentException("inner")).apply { + addSuppressed(RuntimeException("suppressed")) + } + + val report = generate(exception) + + println(report) + assertTrue(report.isNotEmpty()) + } + + @Test + fun `version is the installed APK versionCode`() { + val report = generate(IllegalStateException("boom")) + + assertTrue(report.contains("* Version: `$INSTALLED_VERSION_CODE`")) + } + + @Test + fun `version falls back to BuildConfig versionCode when package info is unavailable`() { + every { packageManager.getPackageInfo(PACKAGE_NAME, 0) } throws PackageManager.NameNotFoundException() + + val report = generate(IllegalStateException("boom")) + + assertTrue(report.contains("* Version: `${BuildConfig.VERSION_CODE}`")) + } + + @Test + fun `version contains build number when it is set`() { + every { context.resources.getString(R.string.buildNumber) } returns "123" + + val report = generate(IllegalStateException("boom")) + + assertTrue(report.contains("* Version: `$INSTALLED_VERSION_CODE (build #123)`")) + } + + @Test + fun `report contains version name and supported ABIs`() { + val report = generate(IllegalStateException("boom")) + + assertTrue(report.contains("* Version name: `${BuildConfig.VERSION_NAME}`")) + assertTrue(report.contains("* Supported ABIs: `arm64-v8a, armeabi-v7a`")) + } + + @Test + fun `stack trace contains thread name, exception and cause`() { + val exception = IllegalStateException("outer", IllegalArgumentException("inner")) + + val report = generate(exception) + + assertTrue(report.contains("Exception in thread \"$THREAD_NAME\" java.lang.IllegalStateException: outer")) + assertTrue(report.contains("Caused by: java.lang.IllegalArgumentException: inner")) + } + + @Test + fun `stack trace contains suppressed exceptions`() { + val exception = IllegalStateException("outer").apply { + addSuppressed(IllegalArgumentException("suppressed")) + } + + val report = generate(exception) + + assertTrue(report.contains("Suppressed: java.lang.IllegalArgumentException: suppressed")) + } + + @Test + fun `short stack trace is not truncated`() { + val report = generate(IllegalStateException("boom")) + + assertFalse(report.contains(ErrorReportGenerator.TRUNCATION_MARKER)) + } + + @Test + fun `long stack trace is truncated to stay below the Intent size limit`() { + val longMessage = "x".repeat(ErrorReportGenerator.MAX_STACK_TRACE_LENGTH * 2) + + val report = generate(IllegalStateException(longMessage)) + + assertTrue(report.contains(ErrorReportGenerator.TRUNCATION_MARKER)) + assertTrue(report.length < ErrorReportGenerator.MAX_STACK_TRACE_LENGTH * 2) + } + + @Test + fun `truncated stack trace keeps both the outermost exception and the root cause`() { + val longMessage = "x".repeat(ErrorReportGenerator.MAX_STACK_TRACE_LENGTH * 2) + val rootCause = IllegalArgumentException("root cause") + + val report = generate(IllegalStateException(longMessage, rootCause)) + + assertTrue(report.contains(ErrorReportGenerator.TRUNCATION_MARKER)) + assertTrue(report.contains("java.lang.IllegalStateException")) + assertTrue(report.contains("Caused by: java.lang.IllegalArgumentException: root cause")) + } + + @Test + fun `report is still created when the cause chain is circular`() { + val first = IllegalStateException("first") + val second = IllegalArgumentException("second", first) + first.initCause(second) + + val report = generate(first) + + assertTrue(report.contains("CIRCULAR REFERENCE")) + } +} diff --git a/app/src/test/java/com/nextcloud/client/errorhandling/ExceptionHandlerTest.kt b/app/src/test/java/com/nextcloud/client/errorhandling/ExceptionHandlerTest.kt new file mode 100644 index 000000000000..85939563d0f6 --- /dev/null +++ b/app/src/test/java/com/nextcloud/client/errorhandling/ExceptionHandlerTest.kt @@ -0,0 +1,83 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.nextcloud.client.errorhandling + +import android.content.Context +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class ExceptionHandlerTest { + + companion object { + private const val REPORT = "report" + } + + private val thread = Thread("main") + private val crash = IllegalStateException("crash") + + private val defaultExceptionHandler = mockk(relaxed = true) + private val reportGenerator = mockk() + private val shownReports = mutableListOf() + + private var showReport: (String) -> Unit = { shownReports.add(it) } + + @Before + fun setUp() { + every { reportGenerator.generate(thread, crash) } returns REPORT + } + + private fun handleCrash() { + val handler = ExceptionHandler(mockk(), defaultExceptionHandler, reportGenerator) { showReport(it) } + + handler.uncaughtException(thread, crash) + } + + @Test + fun `report is shown and original crash is passed to the platform handler`() { + handleCrash() + + assertEquals(listOf(REPORT), shownReports) + verify(exactly = 1) { defaultExceptionHandler.uncaughtException(thread, crash) } + } + + @Test + fun `original crash is passed to the platform handler when report generation fails`() { + val reportFailure = IllegalArgumentException("report failed") + every { reportGenerator.generate(thread, crash) } throws reportFailure + + handleCrash() + + verify(exactly = 1) { defaultExceptionHandler.uncaughtException(thread, crash) } + assertTrue(crash.suppressed.contains(reportFailure)) + } + + @Test + fun `original crash is passed to the platform handler when showing the report throws an error`() { + val reportFailure = OutOfMemoryError("no memory for report") + showReport = { throw reportFailure } + + handleCrash() + + verify(exactly = 1) { defaultExceptionHandler.uncaughtException(thread, crash) } + assertTrue(crash.suppressed.contains(reportFailure)) + } + + @Test + fun `crash is not added to itself when report generation rethrows it`() { + every { reportGenerator.generate(thread, crash) } throws crash + + handleCrash() + + verify(exactly = 1) { defaultExceptionHandler.uncaughtException(thread, crash) } + assertTrue(crash.suppressed.isEmpty()) + } +}