Jørund Amsen
05/14/2024, 2:19 PMfun 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
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.Youssef Shoaib [MOD]
05/14/2024, 3:19 PMcause
exception or a suppressedException
Joffrey
06/11/2024, 2:39 PMJoffrey
06/11/2024, 2:39 PMmost logging tools shows my wrapper rather than the often usefull underlying ExceptionThat is strange. Most logging tools should show the full stacktrace including the cause.
Jørund Amsen
06/11/2024, 2:48 PMIf you want to add metadata to an exception, why would you want to catch the original one? Most likely your high-level exception wrapper makes more sense and should be the one to catchUsually I have metadata at a particular call-site I won't have at a top-level exception handler unless it's somehow thread context or something similar
That is strange. Most logging tools should show the full stacktrace including the cause.This is true, but it will be buried in the stack-trace, and not catcheable based on the original type, And slightly harder to find in logs since it won't be top-level exception
Joffrey
06/11/2024, 2:53 PMUsually I have metadata at a particular call-site I won't have at a top-level exception handler unless it's somehow thread context or something similarI think you missed my point. At the particular call site where you have metadata, you create a wrapper exception with properties that contain this metadata. Later at a high-level catch-site, you want to catch the high-level exception and access the metadata.
class AdminNotFoundException(val adminId: String, cause: Throwable) : Exception("Admin not found with ID $adminId", cause)
fun getAdmins(adminId: String) {
try {
getUsers(adminId)
} catch (e: Exception) {
throw AdminNotFoundException(adminId, e)
}
}
// in some place
try {
someFunctionThatEventuallyCallsGetAdmins()
} catch(e: AdminNotFoundException) {
// do something with e.adminId
}
Joffrey
06/11/2024, 2:55 PM