0
0
Spring Bootframework~5 mins

Validation error responses in Spring Boot

Choose your learning style9 modes available
Introduction

Validation error responses tell users what went wrong when they send wrong or incomplete data. This helps users fix their input easily.

When a user submits a form with missing or wrong information.
When an API receives data that does not meet the required rules.
When you want to give clear feedback about input mistakes.
When you want to prevent bad data from being saved or processed.
Syntax
Spring Boot
@RestController
public class MyController {

    @PostMapping("/submit")
    public ResponseEntity<String> submitData(@Valid @RequestBody MyData data, BindingResult result) {
        if (result.hasErrors()) {
            // handle errors
        }
        return ResponseEntity.ok("Success");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
            errors.put(error.getField(), error.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errors);
    }
}

Use @Valid to trigger validation on input data.

Use @ExceptionHandler to catch validation errors and send a clear response.

Examples
Simple check for errors inside the controller method.
Spring Boot
@PostMapping("/user")
public ResponseEntity<String> addUser(@Valid @RequestBody User user, BindingResult result) {
    if (result.hasErrors()) {
        return ResponseEntity.badRequest().body("Invalid user data");
    }
    return ResponseEntity.ok("User added");
}
Centralized error handler that returns field-specific messages.
Spring Boot
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleErrors(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getFieldErrors().forEach(error ->
        errors.put(error.getField(), error.getDefaultMessage()));
    return ResponseEntity.badRequest().body(errors);
}
Sample Program

This Spring Boot controller accepts a user with a name. If the name is blank, it sends back a clear error message in JSON format.

Spring Boot
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    public static class User {
        @NotBlank(message = "Name must not be blank")
        public String name;
    }

    @PostMapping("/users")
    public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
        return ResponseEntity.ok("User created: " + user.name);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.put(error.getField(), error.getDefaultMessage());
        }
        return ResponseEntity.badRequest().body(errors);
    }
}
OutputSuccess
Important Notes

Always add meaningful messages to your validation annotations for better feedback.

Use @ExceptionHandler to keep your controller methods clean and handle errors in one place.

Summary

Validation error responses help users fix their input by telling them what is wrong.

Use @Valid and @ExceptionHandler in Spring Boot to handle validation errors.

Return clear, field-specific messages in JSON for easy understanding.