Java/Kotlin/Spring Boot。如何在异常发生时自动获取参数值?

标签 java spring-boot kotlin stack-trace interceptor

考虑到我们正在使用 KotlinSpring 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/

相关文章:

java - 如何解决 "glUtilsParamSize"问题

java - 正确设置 Maven 3

java - spring boot 启动rest服务失败

Android 如何在 Kotlin 中以编程方式设置多个重力值?

android - 安装 Scarlet 时重复依赖项

java - 在 ANTLR4 中遍历解析树时处理错误的惯用方法是什么?

java - IBM 移动第一 : Invoking adapter from Java- InvokeProcedure

java - 如何使用 Java 将带有一些数据的图像存储在 MongoDB 中

java - 如何为 Spring Boot 应用程序配置嵌入式 Tomcat 虚拟主机?

不在范围内的 Kotlin 变量?