Search code examples
springspring-bootkotlinspring-mvcspring-data

ResponseEntity body attributes missing in Springboot with Kotlin


I am developing a spring boot server and I am tryin to implement a custom exception handler for Validations

data class UserDtoIn(
    @field:NotBlank(message = "Please add a username")
    var username: String = "",
    @field:NotBlank(message = "Please add your password")
    var password: String = "",
    @field:Email(message = "Please add a correct email")
    var email: String = ""
)
@JsonInclude(JsonInclude.Include.NON_NULL)
class ErrorResponse(
    val status: Int = 0,
    val message: String? = null,
    var stackTrace: String? = null,
    var errors: MutableList<ValidationError>? = null,
) {
    class ValidationError(
        private val field: String? = null,
        private val message: String? = null
    )

    fun addValidationError(field: String?, message: String?) {
        if (Objects.isNull(errors)) {
            errors = ArrayList()
        }
        errors!!.add(ValidationError(field, message))
    }
}
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    override fun handleMethodArgumentNotValid(
        ex: MethodArgumentNotValidException,
        headers: HttpHeaders,
        status: HttpStatusCode,
        request: WebRequest
    ): ResponseEntity<Any>? {
        val errorResponse = ErrorResponse(
            HttpStatus.UNPROCESSABLE_ENTITY.value(),
            "Validation error. Check 'errors' field for details."
        )
        for (fieldError in ex.bindingResult.fieldErrors) {
            errorResponse.addValidationError(fieldError.field, fieldError.defaultMessage)
        }
        return ResponseEntity.unprocessableEntity().body(errorResponse)
    }

the response I got for a bad request is this:

{
    "status": 422,
    "message": "Validation error. Check 'errors' field for details.",
    "errors": [
        {},
        {}
    ]
}

Any opinions? The error response message is showing properly, but the Error objects seems to be null, but the entries are created for them. (in the inDto i have 2 bad fields and i have 2 brackets in the errors)

in debug mode my errorResponse looks like this


Solution

  • The two fields you had in ValidationError class are private, basically for private fields as per java style jackson uses getters and setters for serialization and deserialization.

    Since it's kotlin programming and they are defined with val keyword, you can define them as public, and you don't need to assign null since the default it is default value for String type.

    class ValidationError(
        val field: String?,
        val message: String?
    )