考虑到我们正在使用Kotlin
, Spring Boot
、注释等相关库。
如果我们的代码抛出异常,我们如何在异常发生时自动检索方法参数值?
我们可以使用 AOP、Spring 拦截器或其他技术来做到这一点吗?
我们希望用它来丰富我们的错误消息,以便我们可以从错误发生的地方复制错误。
请注意,我们正在寻找一种解决方案,我们不需要注释所有可能的方法,而是需要在发生异常时处理代码。我们可以使用 Java 堆栈跟踪元素来检索一些有用的信息,例如发生异常的方法、行和文件,但我们没有那里的参数值。
在 Spring 中,我们有控制器建议功能,我们可以使用它来处理所有异常,因此我们想为此目的放置一些东西,例如。
Edit
添加一些示例代码:
fun exceptionHandler(throwable: Throwable) {
logger.severe("""
Error ${throwable.message}
File: ${throwable.stackTrace[2].fileName}
Class: ${throwable.stackTrace[2].className}
Method: ${throwable.stackTrace[2].methodName}
Line: ${throwable.stackTrace[2].lineNumber}
Parameters: ## Somehow get the parameters values here, in this case "Hello, 1, false"
""".trimIndent())
}
fun myController() {
myMethodWithErrors("Hello", 1, false)
}
fun myMethodWithErrors(param1: String, param2: Int, param3: Boolean) {
throw RuntimeException("Some bad thing happened here when executing this code.")
}