commonMain.com.caesarealabs.loggy.shared.SerializableThrowable.kt Maven / Gradle / Ivy
The newest version!
package com.caesarealabs.loggy.shared
import kotlinx.serialization.Serializable
/**
* An alternative to [Throwable] that is serializable to send across the network. The list represents the chain of "caused by:".
* Don't use this class directly, rather convert it to and from [Throwable] with [toSerializable] and [selfToSerializable].
*/
typealias SerializableThrowable = List
@Serializable
data class SerializableThrowableElement(val className: String, val message: String, val stacktrace: String) {
override fun toString(): String {
return "$className: $message\n$stacktrace"
}
}
fun Throwable.toSerializable(): SerializableThrowable {
val elements = mutableListOf()
var current: Throwable? = this
while (current != null) {
elements.add(current.selfToSerializable())
current = current.cause
}
return elements
}
private fun Throwable.selfToSerializable(): SerializableThrowableElement {
return SerializableThrowableElement(this::class.qualifiedName!!, message ?: "", stackTraceToString())
}