aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/utils/telemetry/ExceptionContextValue.kt
blob: 96b70ecc84be24669c30f61e8f8194edec9b1966 (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
39
package moe.nea.ledger.utils.telemetry

import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject

class ExceptionContextValue(val exception: Throwable) : ContextValue {
	val stackTrace by lazy {
		exception.stackTraceToString()
	}

	override fun serialize(): JsonElement {
		val jsonObject = JsonObject()
		jsonObject.addProperty("exception_stackTrace", stackTrace)
		jsonObject.add("exception_structure", walkExceptions(exception, 6))
		return jsonObject
	}

	private fun walkExceptions(exception: Throwable, searchDepth: Int): JsonElement {
		val obj = JsonObject()
		obj.addProperty("class", exception.javaClass.name)
		obj.addProperty("message", exception.message)
		// TODO: allow exceptions to implement an "extra info" interface
		if (searchDepth > 0) {
			val cause = exception.cause
			if (cause != null && cause !== exception) {
				obj.add("cause", walkExceptions(cause, searchDepth - 1))
			}
			val suppressions = JsonArray()
			for (suppressedException in exception.suppressedExceptions) {
				suppressions.add(walkExceptions(suppressedException, searchDepth - 1))
			}
			if (suppressions.size() > 0) {
				obj.add("suppressions", suppressions)
			}
		}
		return obj
	}
}