考虑这个简单的类:
class Foo {
fun a(x: Int) = ...
fun b(x: Int) = ...
fun c(x: Int, y: Int) = ...
}
任何类函数都可能抛出异常。在那种情况下,我想记录方法的输入参数。我可以在每个方法中手动编写try-catch块 - 但它们会使代码变得丑陋和重复。或者 - 我可以尝试找到一些很好的解决方案来保持代码整洁。
有没有办法自动生成try-catch块并定义它应该做什么?类似的东西:
class Foo {
@WithTryCatch fun a(x: Int) = ...
@WithTryCatch fun b(x: Int) = ...
@WithTryCatch fun c(x: Int, y: Int) = ...
fun executeOnCatch() {
log.fatal(...)
}
}
答案 0 :(得分:3)
您可以创建一个更高阶的函数,将代码块传递给处理异常:
inline fun <T,R> safeExecute(block: (T)->R): R {
try{
return block()
} catch (e: Exception){
// do your handle actions
}
}
现在你可以在你的功能中使用它了:
fun a(x: Int) = safeExecute{
//todo
}
使用简单的概念,这是一个简单,清晰,可读的解决方案。
编辑:
为了启用错误记录,您可以传递类型为()->String
的第二个参数,以便在出现错误时提供消息。
inline fun <T,R> safeExecute(errorMsgSupplier: () -> String, block: (T) -> R): R {
try{
return block()
} catch (e: Exception){
// do your handle actions
log.fatal(errorMsgSupplier())
}
}