Learn / Frameworks / Spring Boot / Validation and Problem Details

Spring Boot · Lesson 7 of 15

Validation and Problem Details

Bean Validation, MethodArgumentNotValidException and RFC 7807 bodies.

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 6: Spring Security and JWT

What you will learn

  • Annotate a DTO
  • Return ProblemDetail
  • Map a domain error

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Bean Validation on the DTO plus a @ControllerAdvice that returns ProblemDetail gives clients a consistent error shape.

The DTO

public record CreateTaskRequest(
    @NotBlank @Size(max = 100) String title,
    @NotNull Boolean done
) {}

Problem details

@RestControllerAdvice
public class ApiErrors {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail validation(MethodArgumentNotValidException ex) {
        ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        pd.setTitle("Validation failed");
        pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
            .map(fe -> Map.of("field", fe.getField(), "message", fe.getDefaultMessage()))
            .toList());
        return pd;
    }

    @ExceptionHandler(NoSuchElementException.class)
    ProblemDetail missing(NoSuchElementException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}

Return 422 only if you distinguish "malformed JSON" (400) from "semantically invalid" (422). Either way, be consistent.

Up next · Lesson 8Transactions and Locking@Transactional boundaries, isolation and optimistic locking.