How do people handle wanting to add contextual inf...
# codingconventions
j
How do people handle wanting to add contextual information to an exception that is thrown? Say I have a function getUser() that can throw exceptions of various types for various (unknown) reasons. This function can be called multiple places, for example in getAdmins() and getCustomers() and I'd like to append contextual information in the callplace, to say what I was trying to do when the function failed
Copy code
fun getAdmins(adminId: String) {
    try {
        getUsers(adminId)
    } catch (e: Exception) {
        // "Failed fetching admin by $adminId"
    }
}
Now I could wrap the existing exception in a new custom exception MyUserException("Failed ...", e) However this means I cannot catch the underlying exception specifically, and in most logging tools shows my wrapper rather than the often usefull underlying Exception. I could rethrow the exception, with a log statement
Copy code
catch (e: Exception){
   log.error("Failed fetching admin...", e)
   throw e
}
However I dislike having multiple log entries from a single error, and puts the responsibility on me for "connecting the dots" of the different log statements.
y
You can add a
cause
exception or a
suppressedException