Home > Software design >  How to log exceptions within kotlin predicates?
How to log exceptions within kotlin predicates?

Time:01-22

Given something like:

fun List<Something>.getWidget(): MyWidget = 
    first { widget ->
        // widget getting code here
    }

I want to catch and log the possible NoSuchElementException. What's the best way to do this within a predicate?

Thanks!

CodePudding user response:

Is this maybe what you want?

fun List<Something>.getWidget(): MyWidget = 
    try {
        first { widget ->
            // widget getting code here
        }
    } catch (e: NoSuchElementException) {
        //do whatever you want here, like logging
        throw e //rethrow it
    }

Although I maybe think you misunderstand what NoSuchElementException actually means. That exception doesn't happen in the predicate. It is thrown when for none of the Something objects the predicate is true

CodePudding user response:

The first function throws if it doesn't find an element matching the predicate, so @IvoBeckers 's answer is what you want (wrap the whole call in a try/catch). But you might just want to use firstOrNull instead, if you're handling the missing item case and not just letting it crash (which would log the stacktrace anyway)

fun List<Something>.getWidget(): MyWidget = 
    firstOrNull { widget ->
        // widget getting code here
    } ?: defaultWidget.also { Log.w("ohno") }
  •  Tags:  
  • Related