6.6.3 - Alpha5 - 优化脚本异常消息在控制台的显示内容与格式

This commit is contained in:
SuperMonster003
2025-05-23 21:24:41 +08:00
parent 2f0d3a7409
commit 3168f2d4bb
14 changed files with 61 additions and 59 deletions

View File

@@ -14,6 +14,7 @@ import org.autojs.autojs.runtime.api.augment.events.Events
import org.autojs.autojs.runtime.exception.ScriptException
import org.autojs.autojs.runtime.exception.ScriptInterruptedException
import org.autojs.autojs.runtime.exception.WrappedIllegalArgumentException
import org.autojs.autojs.runtime.exception.WrappedIllegalArgumentException.Companion.getRefinedStackTrace
import org.autojs.autojs.runtime.exception.WrappedRuntimeException
import org.autojs.autojs.util.RhinoUtils
import org.autojs.autojs.util.RhinoUtils.DEFAULT_CALLER
@@ -437,38 +438,28 @@ abstract class Augmentable(private val scriptRuntime: ScriptRuntime? = null) : F
else -> targetEx
}
else -> t
}
}.also { it.printStackTrace() }
if (ScriptInterruptedException.causedByInterrupt(e)) {
throw e
}
val funcNameSuffix = if (funcName != funcNameAlias) " (${globalContext.getString(R.string.text_alias)}: $funcNameAlias)" else ""
val methodDescription = "$key.$funcName$funcNameSuffix"
val message = globalContext.getString(R.string.error_failed_to_invoke_method_with_description, methodDescription)
val message = globalContext.getString(R.string.error_failed_to_call_method, methodDescription)
val niceMessage = when (val errMsg = e.message) {
null -> message
null -> e.takeUnless { it is WrappedIllegalArgumentException }?.stackTraceToString()?.let {
getRefinedStackTrace(message, it)
} ?: message
else -> {
val refined = errMsg.replaceFirst(Regex("^(Wrapped )?\\w*(\\.\\w+)*(Exception|Error): "), "")
val trailingDot = if (refined.endsWith(".")) "" else "."
"$message. $refined$trailingDot\n$e"
when (e is WrappedIllegalArgumentException) {
true -> "$message. $refined$trailingDot"
else -> "$message. $refined$trailingDot\n$e"
}
}
}
e.printStackTrace()
when (e) {
is WrappedIllegalArgumentException -> {
// @Hint by SuperMonster003 on Oct 31, 2024.
// ! Here we force WrappedIllegalArgumentException to be converted to RuntimeException
// ! to prevent Rhino JavaScript code's try..catch blocks from catching this important exception.
// ! Additionally, WrappedIllegalArgumentException itself inherits from WrappedException,
// ! so the exception's code line number will be included when printing the error stack trace.
// ! zh-CN:
// ! 这里强制将 WrappedIllegalArgumentException 转换为 RuntimeException,
// ! 是为了让 Rhino JavaScript 代码的 try..catch 块无法捕获这个重要异常.
// ! 另外 WrappedIllegalArgumentException 本身继承了 WrappedException,
// ! 因此在打印错误堆栈信息时会包含异常所在的 code line number (代码行号).
throw RuntimeException(niceMessage, e)
}
else -> throw WrappedRuntimeException(niceMessage, e)
}
throw WrappedRuntimeException(niceMessage)
}
}, NOT_CONSTRUCTABLE)
destination.defineProperty(funcNameAlias, f, attributes)

View File

@@ -6,32 +6,7 @@ import org.mozilla.javascript.EvaluatorException
// @Hint by SuperMonster003 on Oct 31, 2024.
// ! This class include the exception's code line number when printing the error stack trace.
// ! zh-CN: 当前类可在打印错误堆栈信息时包含异常所在的 code line number (代码行号).
class WrappedIllegalArgumentException(detailMessage: String) : EvaluatorException(run {
var droppedFormer = false
var droppedLatter = false
val result = mutableListOf<String>()
for (e in Thread.currentThread().stackTrace) {
if ("$e".startsWith(WrappedIllegalArgumentException::class.java.name)) {
droppedFormer = true
result.clear()
continue
}
if ("$e".contains(Regex("^(java.lang.reflect.Method.invoke|org.mozilla.javascript.Interpreter)"))) {
droppedLatter = true
break
}
result += "$e"
}
if (droppedFormer) result.add(0, ELLIPSIS_MARK)
if (droppedLatter) result.add(ELLIPSIS_MARK)
buildString {
appendLine(detailMessage)
appendLine()
appendLine(if (droppedFormer || droppedLatter) "Stack trace (partial):" else "Stack trace:")
appendLine()
appendLine(result.joinToString("\n") { " $it" })
}
}) {
class WrappedIllegalArgumentException(detailMessage: String) : EvaluatorException(getRefinedStackTrace(detailMessage)) {
private val exception = IllegalArgumentException(details())
@@ -66,7 +41,53 @@ class WrappedIllegalArgumentException(detailMessage: String) : EvaluatorExceptio
companion object {
private const val ELLIPSIS_MARK = "... ..."
private const val LINE_INDENT = 4
@JvmStatic
@JvmOverloads
fun getRefinedStackTrace(detailMessage: String, stackTrackString: String? = null): String {
var withAtSymbol = false
var droppedFormer = false
var droppedLatter = false
val result = mutableListOf<String>()
val stackTraces = stackTrackString?.split("\n") ?: Thread.currentThread().stackTrace.map { it.toString() }
for (e in stackTraces) {
if (e.startsWith(WrappedIllegalArgumentException::class.java.name)) {
droppedFormer = true
withAtSymbol = false
result.clear()
continue
}
if (e.contains(Regex("^(\\s*at\\s+)?\\s*(java.lang.reflect.Method.invoke|org.mozilla.javascript.Interpreter)"))) {
droppedLatter = true
break
}
if (e.contains(Regex("^\\s*at\\s+"))) {
withAtSymbol = true
}
result += e.trimStart()
}
if (droppedFormer) result.add(0, ELLIPSIS_MARK)
if (droppedLatter) result.add(ELLIPSIS_MARK)
if (result.isEmpty()) return detailMessage
return buildString {
appendLine(if (detailMessage.endsWith(".")) detailMessage else "$detailMessage.")
appendLine()
appendLine(if (droppedFormer || droppedLatter) "Stack trace (partial):" else "Stack trace:")
appendLine()
appendLine(result.joinToString("\n") {
when {
!withAtSymbol -> " ".repeat(LINE_INDENT) + it
it.contains(Regex("^\\s*at\\s+")) -> " ".repeat(LINE_INDENT) + it
it == ELLIPSIS_MARK -> " ".repeat(LINE_INDENT) + it
else -> it
}
})
}
}
}
}
}

View File

@@ -187,7 +187,6 @@
<string name="error_failed_to_grant_shizuku_access">فشل منح Shizuku حق الوصول</string>
<string name="error_failed_to_instantiate">فشل إنشاء المثيل \"%s\"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[فشل إنشاء المثيل \"%1$s\": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">فشل في استدعاء الطريقة %1$s</string>
<string name="error_failed_to_render_content">فشل في عرض المحتوى</string>
<string name="error_failed_to_retrieve_released_notes">فشل في استرداد معلومات الإصدار</string>
<string name="error_failed_to_retrieve_version_histories">تعذّر جلب سجل الإصدارات</string>

View File

@@ -182,7 +182,6 @@
<string name="error_failed_to_grant_shizuku_access">Failed to grant Shizuku access</string>
<string name="error_failed_to_instantiate">Failed to instantiate "%s"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[Failed to instantiate "%1$s": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">Failed to invoke method %1$s</string>
<string name="error_failed_to_render_content">Failed to render content</string>
<string name="error_failed_to_retrieve_released_notes">Failed to retrieve release notes</string>
<string name="error_failed_to_retrieve_version_histories">Failed to retrieve version histories</string>

View File

@@ -185,7 +185,6 @@
<string name="error_failed_to_grant_shizuku_access">Fallo en la concesión de permisos Shizuku</string>
<string name="error_failed_to_instantiate">Error al instanciar \"%s\"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[Error al instanciar \"%1$s\": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">Error al invocar el método %1$s</string>
<string name="error_failed_to_render_content">Error al renderizar el contenido</string>
<string name="error_failed_to_retrieve_released_notes">No se pudo obtener la información de la versión</string>
<string name="error_failed_to_retrieve_version_histories">No se pudo obtener el historial de versiones</string>

View File

@@ -185,7 +185,6 @@
<string name="error_failed_to_grant_shizuku_access">Échec de l\'octroi de la permission de Shizuku</string>
<string name="error_failed_to_instantiate">Échec de l\'instanciation de \"%s\"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[Échec de l\'instanciation de \"%1$s\": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">Échec de l\'appel de la méthode %1$s</string>
<string name="error_failed_to_render_content">Impossible d\'afficher le contenu</string>
<string name="error_failed_to_retrieve_released_notes">Échec de la récupération des informations de version</string>
<string name="error_failed_to_retrieve_version_histories">Impossible de récupérer l\'historique des versions</string>

View File

@@ -186,7 +186,6 @@
<string name="error_failed_to_grant_shizuku_access">Shizuku の権限付与に失敗しました</string>
<string name="error_failed_to_instantiate">\"%s\" のインスタンス化に失敗しました</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[インスタンス化 \"%1$s\" に失敗しました: [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">メソッド %1$s の呼び出しに失敗しました</string>
<string name="error_failed_to_render_content">コンテンツの表示に失敗しました</string>
<string name="error_failed_to_retrieve_released_notes">バージョン情報の取得に失敗しました</string>
<string name="error_failed_to_retrieve_version_histories">バージョン履歴を取得できません</string>

View File

@@ -187,7 +187,6 @@
<string name="error_failed_to_grant_shizuku_access">Shizuku 권한을 부여하지 못했습니다</string>
<string name="error_failed_to_instantiate">\"%s\" 인스턴스 생성에 실패했습니다</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[인스턴스 생성 \"%1$s\" 에 실패했습니다: [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">메소드 %1$s 호출에 실패했습니다</string>
<string name="error_failed_to_render_content">콘텐츠 렌더링에 실패했습니다</string>
<string name="error_failed_to_retrieve_released_notes">버전 정보를 가져오지 못했습니다</string>
<string name="error_failed_to_retrieve_version_histories">버전 기록을 가져올 수 없습니다</string>

View File

@@ -185,7 +185,6 @@
<string name="error_failed_to_grant_shizuku_access">Не удалось предоставить права на использование Shizuku</string>
<string name="error_failed_to_instantiate">Ошибка создания экземпляра \"%s\"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[Ошибка создания экземпляра \"%1$s\": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">Ошибка вызова метода %1$s</string>
<string name="error_failed_to_render_content">Не удалось отобразить содержимое</string>
<string name="error_failed_to_retrieve_released_notes">Не удалось получить информацию о версии</string>
<string name="error_failed_to_retrieve_version_histories">Не удалось получить историю версий</string>

View File

@@ -183,7 +183,6 @@
<string name="error_failed_to_grant_shizuku_access">Shizuku 權限授予失敗</string>
<string name="error_failed_to_instantiate">實例 \"%s\" 創建失敗</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[實例 \"%1$s\" 創建失敗: [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">方法 %1$s 調用失敗</string>
<string name="error_failed_to_render_content">內容渲染失敗</string>
<string name="error_failed_to_retrieve_released_notes">獲取版本信息失敗</string>
<string name="error_failed_to_retrieve_version_histories">獲取版本歷史失敗</string>

View File

@@ -183,7 +183,6 @@
<string name="error_failed_to_grant_shizuku_access">Shizuku 許可權授予失敗</string>
<string name="error_failed_to_instantiate">例項 \"%s\" 建立失敗</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[例項 \"%1$s\" 建立失敗: [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">方法 %1$s 呼叫失敗</string>
<string name="error_failed_to_render_content">內容渲染失敗</string>
<string name="error_failed_to_retrieve_released_notes">獲取版本資訊失敗</string>
<string name="error_failed_to_retrieve_version_histories">獲取版本歷史失敗</string>

View File

@@ -183,7 +183,6 @@
<string name="error_failed_to_grant_shizuku_access">Shizuku 权限授予失败</string>
<string name="error_failed_to_instantiate">实例 \"%s\" 创建失败</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[实例 \"%1$s\" 创建失败: [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">方法 %1$s 调用失败</string>
<string name="error_failed_to_render_content">内容渲染失败</string>
<string name="error_failed_to_retrieve_released_notes">获取版本信息失败</string>
<string name="error_failed_to_retrieve_version_histories">获取版本历史失败</string>

View File

@@ -413,7 +413,6 @@
<string name="error_failed_to_grant_shizuku_access">Failed to grant Shizuku access</string>
<string name="error_failed_to_instantiate">Failed to instantiate "%s"</string>
<string name="error_failed_to_instantiate_with_cause"><![CDATA[Failed to instantiate "%1$s": [ %2$s ]]]></string>
<string name="error_failed_to_invoke_method_with_description">Failed to invoke method %1$s</string>
<string name="error_failed_to_render_content">Failed to render content</string>
<string name="error_failed_to_retrieve_released_notes">Failed to retrieve release notes</string>
<string name="error_failed_to_retrieve_version_histories">Failed to retrieve version histories</string>