gpt4 book ai didi

java - 自动记录在 catch block 中,仅当注释异常变量时,对于 Java 或 Kotlin

转载 作者:IT老高 更新时间:2023-10-28 13:39:00 26 4
gpt4 key购买 nike

我想为 Java 或 Kotlin 执行此操作:给出下面的代码

try { ...
} catch (@AutoLog e: Exception) { //position1
}

在构建期间自动在位置 1 添加一条日志记录语句。我可以使用 AspectJ 为 catch block 添加代码(适用于 Java 和 Kotlin),但它适用于所有 catch block ,我无法检查 @AutoLog 注释是否存在,只有在存在时才添加代码。所以我想我必须求助于 Java 的 APT(注释处理工具)(或 Kotlin 的 KAPT)?

顺便说一句,我在这里找到了一个 KAPT 代码生成示例:https://github.com/JetBrains/kotlin-examples/tree/master/gradle/kotlin-code-generation ,但它会生成代码来分隔文件,而我想要做的是修改原始文件/类并在 catch block 中添加一条语句。

最佳答案

您可以使用 Kotlin 的一些功能来创建自己的函数,而不是使用注解,这些函数的操作类似于标准 try { ... } catch { ... },但也记录异常.这是一个简单的例子:

sealed class Result<S>

class Success<S>(val value: S) : Result<S>()
class Error<S, E : Throwable>(val error: E) : Result<S>()

fun <S> loggingTry(block: () -> S): Result<S> {
return try {
Success(block())
} catch (e: Throwable) {
Error(e)
}
}

inline infix fun <reified E : Throwable, R> Result<out R>.catch(handler: (E) -> R): R {
return when (this) {
is Success -> value
is Error<*, *> -> if (error is E) {
println("Error $error is being handled") // replace this with your own logging
handler(error)
} else throw error
}
}

fun main(args: Array<String>) {
val x = loggingTry {
1 / 0
} catch { e: ArithmeticException ->
3
}

println("Result: $x")

loggingTry {
1 / 0
} catch { e: NullPointerException ->
println("This won't be called, the exception will just be re-thrown")
}
}

此代码生成以下输出:

Error java.lang.ArithmeticException: / by zero is being handled
Division result was 3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at MainKt$main$1.invoke(Main.kt:34)
at MainKt$main$1.invoke(Main.kt)
at MainKt.loggingTry(Main.kt:8)
at MainKt.main(Main.kt:33)

这不是一个完美的解决方案,因为它更受限制(例如,没有多重捕获)并且语法略有不同,但最终结果是可比较的。

关于java - 自动记录在 catch block 中,仅当注释异常变量时,对于 Java 或 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52694733/

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