Код: Выделить всё
import jakarta.validation.constraints.*;
data class RequestBodyDTO(
@NotBlank(message = "ID is required.")
val id: String
)
Код: Выделить всё
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController("do-something")
@RequestMapping("/command/do-something")
class Handler {
@PostMapping
fun handle(@Valid @RequestBody requestRequestBody: RequestBodyDTO): ResponseEntity {
return ResponseEntity.ok().build()
}
}
Код: Выделить всё
import org.springframework.http.HttpStatus
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
@ControllerAdvice
class ValidationExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationException(
exception: MethodArgumentNotValidException
): Map {
return exception.bindingResult.allErrors.associate { error ->
val fieldName = (error as FieldError).field
val errorMessage = error.defaultMessage
fieldName to errorMessage
}
}
}
POST http://localhost:8080/command/do-something
Я ожидал бы 400 с информацией об отсутствии поля идентификатора. Но я получаю только
Код: Выделить всё
{
"timestamp": "2025-01-09T09:38:11.218+00:00",
"path": "/command/do-something",
"status": 400,
"error": "Bad Request",
"requestId": "94d9009e-2"
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ing-spring
Мобильная версия