英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论