考虑到我们正在使用 Kotlin
、Spring Boot
、注释和其他相关库。
如果我们的代码抛出异常,我们如何在异常发生时自动检索方法参数值?
我们可以使用 AOP、Spring 拦截器或其他技术来做到这一点吗?
我们希望用它来丰富我们的错误消息,以便我们可以从错误发生的地方复制错误。
请注意,我们正在寻找一种解决方案,我们不需要注释所有可能的方法,而是需要在发生异常时处理代码。我们可以使用 Java 堆栈跟踪元素来检索一些有用的信息,例如发生异常的方法、行和文件,但我们没有那里的参数值。
在 Spring 中,我们有 Controller 建议功能,我们可以使用它来处理所有异常,因此我们希望为此目的放置一些东西。
编辑
添加一些示例代码:
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.")
}
最佳答案
我假设您谈论的是其余 API 参数,而不是每个 Java 方法参数。您可以实现controller advice捕获其余 API 调用中的所有异常。
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(value = [Exception::class])
@ResponseBody
fun onException(exception: Exception, request: WebRequest): ResponseEntity<ErrorDetailsClass> {
log.error("error when request with parameters ${request.parameterMap} ")
return buildDetails(request)
}
}
通过这种方式,您既可以检索正确的错误消息,也可以在内部记录一些内容以进行错误跟踪。
关于Java/Kotlin/Spring Boot。如何在异常发生时自动获取参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209758/