Skip to content

Instantly share code, notes, and snippets.

@Krosxx
Created July 16, 2020 03:03
Show Gist options
  • Save Krosxx/aad79f7f000490045c7519392f03b321 to your computer and use it in GitHub Desktop.
Save Krosxx/aad79f7f000490045c7519392f03b321 to your computer and use it in GitHub Desktop.
Call ExceptionHandler for Ktor
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
}
}
}
@Krosxx
Copy link
Author

Krosxx commented Jul 16, 2020

install(ExceptionHandler) {
    onHandler { call, err ->
        call.failed(500, err.message ?: "$err")
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment