gpt4 book ai didi

java - Java/Kotlin/Spring Boot。发生异常时如何自动检索参数值?

转载 作者:行者123 更新时间:2023-12-02 13:12:01 26 4
gpt4 key购买 nike

考虑到我们正在使用KotlinSpring Boot,注释和其他相关库。

如果我们遇到代码抛出异常的情况,那么该如何在异常发生时自动检索方法参数值?

我们可以使用AOP,Spring Interceptor或其他技术来做到这一点吗?

我们希望以此来丰富我们的错误消息,以便我们可以从错误发生的位置复制错误。

请注意,我们正在寻找一种不需要注释所有可能方法的解决方案,而是需要一种在发生异常时可以处理代码的解决方案。我们可以使用Java stacktrace元素来检索一些有用的信息,例如发生异常的方法,行和文件,但是那里没有参数值。

在Spring中,我们具有Controller Advice功能,可用于处理所有异常,因此,例如,为此我们希望在其中放置一些内容。

编辑

添加一些示例代码:

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 - Java/Kotlin/Spring Boot。发生异常时如何自动检索参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com