🎓 A1Learner
🔍
0 of 50 lessons completed

Reading Validation Errors

Reading validation errors means asking Spring what failed. BindingResult collects the failures in the controller.

Collect the failures

BindingResult follows the @Valid value in the method.

public ResponseEntity<?> createTask(@Valid @RequestBody TaskForm form, BindingResult result)

Build a small error map

Each failure names its field and its message.

if (result.hasErrors()) {
    Map<String, String> errors = new HashMap<>();
    result.getFieldErrors().forEach(error ->
            errors.put(error.getField(), error.getDefaultMessage()));
    return ResponseEntity.badRequest().body(errors);
}

Example

package com.example.demo;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    private final TaskRepository repository;

    public TaskController(TaskRepository repository) {
        this.repository = repository;
    }

    @PostMapping("/tasks")
    public ResponseEntity<?> createTask(@Valid @RequestBody TaskForm form, BindingResult result) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            result.getFieldErrors().forEach(error ->
                    errors.put(error.getField(), error.getDefaultMessage()));
            return ResponseEntity.badRequest().body(errors);
        }
        Task task = new Task(form.title(), form.done());
        repository.save(task);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(new TaskView(task.getTitle(), task.isDone()));
    }

    public record TaskForm(
            @NotBlank(message = "Title must not be blank") String title,
            boolean done) {
    }

    public record TaskView(String title, boolean done) {
    }
}

Key points

  • BindingResult follows the @Valid value in the method.
  • hasErrors tells whether any check failed.
  • getFieldErrors lists one failure per field.
  • Each failure names its field and its message.
  • The controller builds a small map from field to message.
  • The map is the 400 answer.

In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The createTask method takes a BindingResult right after the @Valid body. When the title is empty, hasErrors is true. The method builds a map from the field name to its message. The map is sent back with 400. A real title has no errors, so it is saved and answered with 201.

Note

Without BindingResult, Spring answers 400 with its own large error body.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does BindingResult sit in the method?