I use following exception handler:
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
class ExceptionHandlerResolver {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MissingKotlinParameterException::class)
fun missingKotlinParameterException(ex: MissingKotlinParameterException): MyCustomError? {
return MyCustomError(
timestamp = LocalDateTime.now(),
status = HttpStatus.BAD_REQUEST,
exception = ex,
validationMessages = listOf(
ValidationMessage(
field = ex.path.fold("") { result, segment ->
if (segment.fieldName != null && result.isEmpty()) segment.fieldName
else if (segment.fieldName != null) "$result.${segment.fieldName}"
else "$result[${segment.index}]"
},
message = "value is required"
)
)
)
}
}
It supports exception for any Json path, for example: arrayField[1].arrayItemField.childField
MyCustomError and ValidationMessage classes:
data class MyCustomError(
val timestamp: LocalDateTime,
@JsonIgnore val status: HttpStatus,
@JsonIgnore val exception: Exception? = null,
val validationMessages: List<ValidationMessage>? = null
) {
@JsonProperty("status") val statusCode = status.value()
@JsonProperty("error") val statusReasonPhrase = status.reasonPhrase
@JsonProperty("exception") val exceptionClass = exception?.javaClass?.name
@JsonProperty("message") val exceptionMessage = exception?.message
}
data class ValidationMessage(val field: String, val message: String)
@NotNull
is redundant when using Kotlin, how do I validate requests in which a non-null property isn't supplied in the request JSON?") – Conjoint