访问异常中的字段

huangapple go评论117阅读模式
英文:

Accessing a field in an exception

问题

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

数据类 ExceptionDetail(
    val thrownBy: String,
    val calculationStage: Int,
    val code: Int = 0,
    val message: String = "",
)

现在在我的自定义异常中:

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

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

throw CustomException(ExceptionDetail(thrownBy = "inner", calculationStage = 9))
英文:

Is it possible to have more information thrown as an Exception in kotlin?

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

now in my custom exception

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

after I throw it, how can I get details of the exception:

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

答案1

得分: 1

保存异常类中的额外字段:

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

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

catch (e: CustomException) {
  e.detail
}
英文:

Save the extra field in your Exception class:

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

Then you can access it in a catch block:

catch (e: CustomException) {
  e.detail
}

huangapple
  • 本文由 发表于 2023年6月19日 20:31:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定