Merge branch 'jackson-errors'

This commit is contained in:
Hubert Van De Walle 2020-06-15 00:43:46 +02:00
commit 47dc1a582b
2 changed files with 70 additions and 0 deletions

View File

@ -10,6 +10,9 @@ import io.ktor.utils.io.errors.*
fun Application.handleErrors() { fun Application.handleErrors() {
install(StatusPages) { install(StatusPages) {
jacksonErrors()
exception<IOException> { exception<IOException> {
call.respond(HttpStatusCode.BadRequest) call.respond(HttpStatusCode.BadRequest)
} }

View File

@ -0,0 +1,67 @@
package be.vandewalleh.features
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.core.exc.InputCoercionException
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.exc.MismatchedInputException
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.response.*
fun StatusPages.Configuration.jacksonErrors() {
exception<MismatchedInputException> {
val error = InvalidFormatError(it.path.firstOrNull()?.fieldName, it.targetType)
call.respond(HttpStatusCode.BadRequest, error)
}
exception<JsonParseException> {
val error = JsonParseError()
call.respond(HttpStatusCode.BadRequest, error)
}
exception<UnrecognizedPropertyException> {
val error = UnrecognizedPropertyError(it.path[0].fieldName)
call.respond(HttpStatusCode.BadRequest, error)
}
exception<MissingKotlinParameterException> {
val error = MissingKotlinParameterError(it.path[0].fieldName)
call.respond(HttpStatusCode.BadRequest, error)
}
exception<JsonProcessingException> {
call.respond(HttpStatusCode.BadRequest, JsonProcessingError())
}
exception<JsonMappingException> {
if (it.cause is InputCoercionException) {
return@exception call.respond(HttpStatusCode.BadRequest, OutOfRangeError(it.path[0].fieldName))
}
call.respond(HttpStatusCode.BadRequest, JsonProcessingError())
}
}
class InvalidFormatError(val value: Any?, targetType: Class<*>) {
val msg = "Wrong type"
val required = targetType.simpleName
}
class UnrecognizedPropertyError(val field: Any?) {
val msg = "Unrecognized field"
}
class MissingKotlinParameterError(val field: String) {
val msg = "Missing field"
}
class JsonProcessingError {
val msg = "An error occurred while processing JSON"
}
class JsonParseError {
val msg = "Invalid JSON"
}
class OutOfRangeError(val field: String) {
val msg = "Numeric value out of range"
}