Garzec
Garzec
Explore posts from servers
JCHJava Community | Help. Code. Learn.
Created by Garzec on 1/12/2025 in #java-help
How to apply request body validation with error details?
Hello there, I want to apply request body validation to my Spring project
import jakarta.validation.constraints.*;

data class RequestBodyDTO(
@NotBlank(message = "ID is required.")
val iD: String
)
import jakarta.validation.constraints.*;

data class RequestBodyDTO(
@NotBlank(message = "ID is required.")
val iD: String
)
and this endpoint
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController()
@RequestMapping("/foo")
class Handler {
@PostMapping
fun handle(@Valid @RequestBody requestBody: RequestBodyDTO): ResponseEntity<Unit> {
return ResponseEntity.ok().build()
}
}
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController()
@RequestMapping("/foo")
class Handler {
@PostMapping
fun handle(@Valid @RequestBody requestBody: RequestBodyDTO): ResponseEntity<Unit> {
return ResponseEntity.ok().build()
}
}
I thought @Valid would handle it for me but actually the API consumer still gets a 400 without any error details. So the consumer doesn't know what's wrong. After googling around I think Spring doesn't do that for me out of the box. So I created an additional class
import org.springframework.http.HttpStatus
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.*

@ControllerAdvice
class ValidationExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationException(
exception: MethodArgumentNotValidException
): Map<String, String?> {
return exception.bindingResult.allErrors.associate { error ->
val fieldName = (error as FieldError).field
val errorMessage = error.defaultMessage

fieldName to errorMessage
}
}
}
import org.springframework.http.HttpStatus
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.*

@ControllerAdvice
class ValidationExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationException(
exception: MethodArgumentNotValidException
): Map<String, String?> {
return exception.bindingResult.allErrors.associate { error ->
val fieldName = (error as FieldError).field
val errorMessage = error.defaultMessage

fieldName to errorMessage
}
}
}
Unfortunately the result is the same, the API consumer won't get any error details. Is something missing? Do I even need the ValidationExceptionHandler ? How do I achieve this? Thanks! 🙂
56 replies