Coverage Summary for Class: ErrorKt (dev.suresh.plugins)
Class |
Method, %
|
Branch, %
|
Line, %
|
Instruction, %
|
ErrorKt |
0%
(0/4)
|
0%
(0/6)
|
0%
(0/12)
|
0%
(0/97)
|
ErrorKt$errorRoutes$1$1 |
0%
(0/1)
|
0%
(0/2)
|
0%
(0/4)
|
0%
(0/20)
|
ErrorKt$errorRoutes$1$2 |
0%
(0/1)
|
0%
(0/4)
|
0%
(0/6)
|
0%
(0/37)
|
ErrorKt$errorRoutes$1$3 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/12)
|
ErrorKt$errorRoutes$1$4 |
0%
(0/1)
|
|
0%
(0/2)
|
0%
(0/19)
|
Total |
0%
(0/8)
|
0%
(0/12)
|
0%
(0/25)
|
0%
(0/185)
|
package dev.suresh.plugins
import dev.suresh.http.*
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.request.*
import io.ktor.server.response.*
fun Application.errorRoutes() {
install(StatusPages) {
status(HttpStatusCode.Unauthorized) { call, status ->
when {
call.isApi ->
call.respondError(
HttpStatusCode.Unauthorized, "Authorization is required to access this resource")
}
}
exception<Throwable> { call, cause ->
val status =
when (cause) {
is BadRequestException -> HttpStatusCode.BadRequest
else -> HttpStatusCode.InternalServerError
}
call.application.log.error(status.description, cause)
call.respondError(status, cause.message ?: "Unknown error", cause)
}
status(HttpStatusCode.NotFound) { call, _ ->
call.respondRedirect("/app", permanent = true) // 301
}
unhandled {
it.respondError(
HttpStatusCode.NotFound, "The requested URL ${it.request.path()} was not found")
}
}
}
fun userError(message: Any): Nothing = throw BadRequestException(message.toString())
suspend fun ApplicationCall.respondError(
status: HttpStatusCode,
message: String,
cause: Throwable? = null
) =
respond(
status = status,
message =
ErrorStatus(
code = status.value,
message = message,
details = if (debug) cause?.stackTraceToString() else cause?.message))