Skip to content

Commit 6d5f2fc

Browse files
committed
#36 onEach notifier for exception storage mappers
1 parent a468feb commit 6d5f2fc

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

errors/src/commonMain/kotlin/dev/icerock/moko/errors/mappers/ExceptionMappersStorage.kt

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ object ExceptionMappersStorage {
2020
fallback = { MR.strings.moko_errors_unknownError.desc() }
2121
)
2222
)
23+
private val notifiers: MutableList<(Throwable, KClass<*>) -> Unit> = mutableListOf()
2324

2425
private fun <T : Any> getOrCreateContainer(resultClass: KClass<T>): MappersContainer<T> {
2526
val existContainer: MappersContainer<*>? = containers[resultClass]
@@ -125,10 +126,17 @@ object ExceptionMappersStorage {
125126
return null
126127
}
127128

128-
return container.mappers
129+
val mapper: (Throwable) -> T = container.mappers
129130
.firstOrNull { it.isApplied(throwable) }
130131
?.mapper
131132
?: container.fallback
133+
134+
return { exception ->
135+
notifiers.forEach { notifier ->
136+
notifier(exception, resultClass)
137+
}
138+
mapper(exception)
139+
}
132140
}
133141

134142
/**
@@ -193,6 +201,18 @@ object ExceptionMappersStorage {
193201
find(clazz, e)?.invoke(e) ?: throw FallbackValueNotFoundException(clazz)
194202
}
195203
}
204+
205+
/**
206+
* Listen all mappers calls. Useful for logging
207+
*
208+
* @param block - lambda that will be called when exception map to some class
209+
*/
210+
fun onEach(
211+
block: (Throwable, KClass<*>) -> Unit
212+
): ExceptionMappersStorage {
213+
notifiers.add(block)
214+
return this
215+
}
196216
}
197217

198218
/**

0 commit comments

Comments
 (0)