本文介绍了Java/Kotlin/Spring Boot.发生异常时,如何自动检索参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Considering that we are using Kotlin, Spring Boot, annotations and other related libraries.

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

If we have a situation in which our code throws an exception, how could we automatically retrieve the method parameters values in the moment of that exception?

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

Can we do this using AOP, Spring Interceptors or other techniques?

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

We would like to have this to enrich our error messages so we could replicate the errors from where they occurred.

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

Please note that we are searching for a solution that we don't need to annotate all possible methods but something that would handle the code when an exception occurs. We can use the Java stacktrace elements to retrieve some useful information like the method, line and file where the exception occurred but we don't have the parameters values there.

在Spring中,我们具有Controller Advice功能,可用于处理所有异常,因此,例如,我们希望为此添加一些东西.

In Spring we have the Controller Advice feature that we can use to handle all of our exceptions, so we would like to put something there for this purpose, for example.

修改

添加一些示例代码:

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方法参数.您可以实现控制器建议,可捕获其余API调用中的所有异常.

I assume that you were talking about rest API parameters and not every single java method parameter. You can implement controller advice that captures all exceptions in your rest API calls.

@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)
    }
}

通过这种方式,您既可以检索正确的错误消息,也可以在内部记录某些内容以进行错误跟踪.

In this way, you can do both retrieve a proper error message and also log something internally for error tracking purposes.

这篇关于Java/Kotlin/Spring Boot.发生异常时,如何自动检索参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:56