diff --git a/api/src/features/ErrorFeature.kt b/api/src/features/ErrorFeature.kt index ee59c87..adde009 100644 --- a/api/src/features/ErrorFeature.kt +++ b/api/src/features/ErrorFeature.kt @@ -10,6 +10,9 @@ import io.ktor.utils.io.errors.* fun Application.handleErrors() { install(StatusPages) { + + jacksonErrors() + exception { call.respond(HttpStatusCode.BadRequest) } diff --git a/api/src/features/JacksonErrors.kt b/api/src/features/JacksonErrors.kt new file mode 100644 index 0000000..83b2a62 --- /dev/null +++ b/api/src/features/JacksonErrors.kt @@ -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 { + val error = InvalidFormatError(it.path.firstOrNull()?.fieldName, it.targetType) + call.respond(HttpStatusCode.BadRequest, error) + } + exception { + val error = JsonParseError() + call.respond(HttpStatusCode.BadRequest, error) + } + exception { + val error = UnrecognizedPropertyError(it.path[0].fieldName) + call.respond(HttpStatusCode.BadRequest, error) + } + exception { + val error = MissingKotlinParameterError(it.path[0].fieldName) + call.respond(HttpStatusCode.BadRequest, error) + } + exception { + call.respond(HttpStatusCode.BadRequest, JsonProcessingError()) + } + exception { + 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" +}