2022-09-16

Kotlin - Pass a function and its arguments to a reusable handler function

My problem comes from an error handler that I need to write. The handler is meant to catch an error, do an action 'A', and then proceed to retry the original function that failed in the first place. The blocker comes when I need to generalise the handler to be able to accept any function definition.

For example:

fun foo(a: Any) {
  // Do something and return null if unsuccessful
}

fun bar(b: Any, c: Any) {
  // Do something else and return false if unsuccessful
}

fun handler(fn: Function???, args: Array[arguments???]) {
  log.warn("Error has been caught at <${functionName}>, doing action A and retrying")
  // Do action A
  log.warn("Retrying <${functionName}>")
  fn(args)
}

fun main() {
  val resultFoo = foo('bar')
  if (resultFoo == null) {
    handler(foo, ['bar'])
  }

  val resultBar = bar('foo', { 'foo': 'bar' })
  if (!resultBar) {
    handler(bar, ['foo', { 'foo': 'bar' }])
  }
}

As you can see, I have two functions foo and bar with different definitions which I would like to be able to call from handler. Otherwise I would need to copy-paste the body inside handler to each individual function and handle the error inside there. I was hoping to be able to generalise this and be able to reuse it.



No comments:

Post a Comment