kotlin 访问异常中的字段

soat7uwm  于 2023-06-24  发布在  Kotlin
关注(0)|答案(1)|浏览(113)

是否可以在Kotlin中将更多信息作为异常抛出?

data class ExceptionDetail(
    val thrownBy: String,
    val calculationStage: Int,
    val code: Int = 0,
    val message: String = "",
)

现在在我的自定义异常中

class CustomException(message: ExceptionDetail? = null, cause: Throwable? = null) : Exception(
    message?.errorMessage,
    cause,
) {
    constructor(cause: Throwable) : this(null, cause)
}

抛出异常后,如何获取异常的详细信息:

throw CustomException(ExceptionDetail(thrownBy = "inner", calculationStage = 9))
jw5wzhpr

jw5wzhpr1#

在Exception类中保存额外的字段:

class CustomException(val detail: ExceptionDetail? = null, cause: Throwable? = null) : Exception(
    detail?.message,
    cause,
)

然后你可以在catch块中访问它:

catch (e: CustomException) {
  e.detail
}

相关问题