Created
July 16, 2020 03:03
-
-
Save Krosxx/aad79f7f000490045c7519392f03b321 to your computer and use it in GitHub Desktop.
Call ExceptionHandler for Ktor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.ktor.application.* | |
import io.ktor.http.HttpStatusCode | |
import io.ktor.response.respond | |
import io.ktor.util.AttributeKey | |
import io.ktor.util.pipeline.PipelinePhase | |
typealias DoHandlerExp = suspend (ApplicationCall, Throwable) -> Unit | |
class ExceptionHandler( | |
private val onHandler: DoHandlerExp | |
) { | |
class Configuration { | |
internal var onHandler: DoHandlerExp = { call, it -> | |
call.respond(HttpStatusCode.OK, it.message ?: "$it") | |
} | |
fun onHandler(handler: DoHandlerExp) { | |
onHandler = handler | |
} | |
} | |
companion object Feature : ApplicationFeature<Application, Configuration, ExceptionHandler> { | |
override val key: AttributeKey<ExceptionHandler> = AttributeKey("Exception Handler") | |
override fun install(pipeline: Application, configure: Configuration.() -> Unit): ExceptionHandler { | |
val handlerPhase = PipelinePhase("ExceptionHandler") | |
val configuration = Configuration().apply(configure) | |
val feature = ExceptionHandler(configuration.onHandler) | |
pipeline.insertPhaseBefore(ApplicationCallPipeline.Monitoring, handlerPhase) | |
pipeline.intercept(handlerPhase) { | |
kotlin.runCatching { | |
proceed() | |
}.onFailure { | |
it.printStackTrace() | |
feature.onHandler(call, it) | |
} | |
} | |
return feature | |
} | |
} | |
} |
Author
Krosxx
commented
Jul 16, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment