Skip to content

Instantly share code, notes, and snippets.

@toefel18
Created January 23, 2022 20:47
Show Gist options
  • Save toefel18/f39601fbf392a2e7ba7216c063c8e2b4 to your computer and use it in GitHub Desktop.
Save toefel18/f39601fbf392a2e7ba7216c063c8e2b4 to your computer and use it in GitHub Desktop.
import java.lang.Exception
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.javaType
import org.slf4j.Logger
// the handlers should throw, but this throw is here so we can use Nothing
// as return type. By using Nothing, this method can be called without having
// actually return something
fun Logger.errorAndThrow(message: String, handler: (String) -> Unit): Nothing {
error(message)
handler(message)
throw IllegalStateException(message)
}
fun Logger.errorAndThrow(message: String, throwAs: KClass<out Exception>): Nothing {
error(message)
throwAs.constructors
.find { it.parameters.size == 1 && it.parameters.first().type.javaType == String::class.java }
?.let { c -> throw c.call(message) }
throw IllegalStateException("exception type ${throwAs.simpleName} does not have a constructor that accepts a String")
}
fun Logger.errorAndThrow(message: String, exception: Exception, handler: (String, Exception) -> Unit): Nothing {
error(message, exception)
handler(message, exception)
throw IllegalStateException(message)
}
fun Logger.errorAndThrow(message: String, exceptionToLog: Exception, throwAs: KClass<out Exception>): Nothing {
error(message, exceptionToLog)
throwAs.constructors
.find { it.parameters.size == 2
&& it.parameters[0].type.javaType == String::class.java
&& it.parameters[1].type.isSubtypeOf(Throwable::class.starProjectedType)}
?.let { c -> throw c.call(message, exceptionToLog) }
throw IllegalStateException("exception type ${throwAs.simpleName} does not have a constructor that accepts a String and a Throwable")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment