在Kotlin中使用相同的try-catch包装所有内部方法

考虑这个简单的类:

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(...) } } 

您可以创建一个更高阶的函数,将您的代码块传递给并处理异常:

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