How to provide custom exception message for an exception thrown by extension function in Kotlin?

Viewed 465

I have the following Kotlin code:

fun getAdminUser(): User {
    return getAllUsers().first { it.userType == ADMIN } as User
}

If getAllUsers() doesn't have an element that matches the specified predicate, it throws a NoSuchElementException. I'm happy with this exception but would like to override the exception message to provide more context when it fails. Is it possible to do in Kotlin w/o try-catch?

2 Answers

You could use the firstOrNull function to achieve that.

fun getAdminUser(): User {
    return (getAllUsers().firstOrNull { it.userType == ADMIN } as? User) ?: throw NoSuchElementException("Element not found")
}

Use firstOrNull to get first element or have null and use the elvis operator to throw NoSuchElementException.

fun getAdminUser(): User {
    val user = getAllUsers().firstOrNull { it.userType == ADMIN } ?: throw NoSuchElementException("My custom exception message")
    return user as? User ?: IllegalStateException("The element was neither null nor an instance of User class")
}

Otherwise to do it in single line you can do something like this:

fun getAdminUser(): User {
    return getAllUsers().firstOrNull { it.userType == ADMIN }?.also { require(it is User) { "The element was neither null nor an instance of User class" } } ?: throw NoSuchElementException("My custom exception message")
}
Related