aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt
blob: 4ba313efa8746d341a22776ae8fb86ff2ccbb104 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package moe.nea.ledger.utils

import moe.nea.ledger.utils.di.Inject
import moe.nea.ledger.utils.telemetry.ContextValue
import moe.nea.ledger.utils.telemetry.EventRecorder
import moe.nea.ledger.utils.telemetry.Span

class ErrorUtil {

	@Inject
	lateinit var reporter: EventRecorder

	fun report(exception: Throwable, message: String?) {
		Span.current().recordException(reporter, exception, message)
	}

	fun <T> Result<T>.getOrReport(): T? {
		val exc = exceptionOrNull()
		if (exc != null) {
			report(exc, null)
		}
		return getOrNull()
	}

	inline fun <T> catch(
		vararg pairs: Pair<String, ContextValue>,
		crossinline function: () -> T
	): T? {
		return Span.current().enterWith(*pairs) {
			try {
				return@enterWith function()
			} catch (ex: Exception) {
				report(ex, null)
				return@enterWith null
			}
		}
	}
}