Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* 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<String> = 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()
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2022 Álvaro Brey <alvaro@alvarobrey.com>
* SPDX-FileCopyrightText: 2019 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2019 Andy Scherzinger <info@andy-scherzinger>
Expand All @@ -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)
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2019 Andy Scherzinger <info@andy-scherzinger.de>
* 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
Expand All @@ -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)
Expand All @@ -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() }
Expand Down Expand Up @@ -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)
}
}
4 changes: 0 additions & 4 deletions app/src/main/res/layout/activity_show_error.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@
<include layout="@layout/toolbar_standard"
android:id="@+id/toolbar_include"/>

<include
android:id="@+id/empty_list"
layout="@layout/empty_list" />

<ScrollView
android:id="@+id/error_page_container"
android:layout_width="match_parent"
Expand Down
Loading
Loading