Do unwrap even if wrapper exception has suppressed exceptions

This commit is contained in:
Him188 2021-07-16 15:45:48 +08:00
parent 8d41e18cdc
commit dfbe73da9a
4 changed files with 67 additions and 2 deletions

View File

@ -32,8 +32,10 @@ internal class StacktraceException(override val message: String?, private val st
public actual inline fun <reified E> Throwable.unwrap(): Throwable {
if (this !is E) return this
if (suppressed.isNotEmpty()) return this
val e = StacktraceException("Unwrapped exception: $this", this.stackTrace)
for (throwable in this.suppressed) {
e.addSuppressed(throwable)
}
return this.findCause { it !is E }
?.also { it.addSuppressed(e) }
?: this

View File

@ -0,0 +1,32 @@
/*
* Copyright 2019-2021 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
package net.mamoe.mirai.utils
import kotlin.test.Test
import kotlin.test.assertIs
class AndroidUnwrapTest {
@Test
fun test() {
val e =
IllegalStateException(
OutOfMemoryError().initCause(VerifyError()).apply { addSuppressed(UnsatisfiedLinkError()) }
)
val unwrapped = e.unwrap<IllegalStateException>()
unwrapped.printStackTrace()
assertIs<OutOfMemoryError>(unwrapped)
assertIs<VerifyError>(unwrapped.cause)
assertIs<UnsatisfiedLinkError>(unwrapped.suppressed.first())
assertIs<StacktraceException>(unwrapped.suppressed[1])
}
}

View File

@ -25,7 +25,6 @@ public actual fun String.decodeBase64(): ByteArray {
public actual inline fun <reified E> Throwable.unwrap(): Throwable {
if (this !is E) return this
if (suppressed.isNotEmpty()) return this
return this.findCause { it !is E }
?.also { it.addSuppressed(this) }
?: this

View File

@ -0,0 +1,32 @@
/*
* Copyright 2019-2021 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
package net.mamoe.mirai.utils
import kotlin.test.Test
import kotlin.test.assertIs
class JvmUnwrapTest {
@Test
fun test() {
val e =
IllegalStateException(
OutOfMemoryError().initCause(VerifyError()).apply { addSuppressed(UnsatisfiedLinkError()) }
)
val unwrapped = e.unwrap<IllegalStateException>()
unwrapped.printStackTrace()
assertIs<OutOfMemoryError>(unwrapped)
assertIs<VerifyError>(unwrapped.cause)
assertIs<UnsatisfiedLinkError>(unwrapped.suppressed.first())
assertIs<IllegalStateException>(unwrapped.suppressed[1])
}
}