Validation and Exception Handling in REST APIs

Interview Preparation Hub for Backend and Cloud-Native Engineering Roles

1. Introduction

Validation and exception handling are the backbone of robust REST API design. Without validation, APIs risk accepting invalid or malicious data. Without exception handling, APIs risk exposing internal errors or stack traces to clients, leading to poor user experience and security vulnerabilities.

In this guide, we will explore validation and exception handling in Spring MVC in depth. We will cover basic annotations, advanced validation techniques, global exception handling, custom error responses, realistic examples, best practices, common mistakes, and interview notes. By the end, you will have mastered these concepts and be ready to build production-grade REST APIs.

2. Validation Basics

Spring MVC integrates with JSR‑303/JSR‑380 Bean Validation API. This allows developers to annotate fields in DTOs or entities with validation constraints.

  • @NotNull – Ensures a field is not null.
  • @Size(min, max) – Validates string length.
  • @Email – Validates email format.
  • @Pattern – Validates against regex.
  • @Min, @Max – Validates numeric ranges.
public class UserDTO {
  @NotNull(message = "Name cannot be null")
  @Size(min = 2, max = 50)
  private String name;

  @Email(message = "Invalid email format")
  private String email;

  @Min(18)
  private int age;
}
    

In controllers, use @Valid to trigger validation:

@PostMapping("/users")
public ResponseEntity createUser(@Valid @RequestBody UserDTO user) {
  User savedUser = userService.save(user);
  return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
    
Diagram: Validation Flow

Client Request → Controller → @Valid Validation → If Valid → Service → Repository → Response
If Invalid → Exception Thrown → GlobalExceptionHandler → Error Response Returned

3. Advanced Validation Techniques

Beyond basic annotations, Spring supports advanced validation:

  • Custom Validators: Implement ConstraintValidator for custom rules.
  • Validation Groups: Apply different constraints in different contexts.
  • Cross-field Validation: Validate relationships between fields.
  • Internationalization: Externalize validation messages for localization.
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AgeValidator.class)
public @interface ValidAge {
  String message() default "Invalid age";
  Class[] groups() default {};
  Class[] payload() default {};
}

public class AgeValidator implements ConstraintValidator {
  public boolean isValid(Integer age, ConstraintValidatorContext context) {
    return age != null && age >= 18 && age <= 100;
  }
}
    

4. Exception Handling Basics

Exception handling ensures that errors are returned in a consistent format. Spring MVC provides @ControllerAdvice and @ExceptionHandler for global error handling.

@ControllerAdvice
public class GlobalExceptionHandler {

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

  @ExceptionHandler(Exception.class)
  public ResponseEntity handleGenericException(Exception ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                         .body("Error: " + ex.getMessage());
  }
}
    

5. Advanced Exception Handling

Advanced techniques include:

  • Custom Exceptions: Define domain-specific exceptions.
  • Error Codes: Return structured error codes for clients.
  • Problem Details (RFC 7807): Standardized error response format.
  • Logging: Log exceptions for monitoring and debugging.
public class ResourceNotFoundException extends RuntimeException {
  public ResourceNotFoundException(String message) {
    super(message);
  }
}

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity handleResourceNotFound(ResourceNotFoundException ex) {
  return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
    

6. Realistic Examples

Example: E-Commerce API with product validation and exception handling.

public class ProductDTO {
  @NotNull(message = "Product name is required")
  private String name;

  @Min(value = 1, message = "Price must be greater than 0")
  private double price;
}

@PostMapping("/products")
public ResponseEntity addProduct(@Valid @RequestBody ProductDTO product) {
  return ResponseEntity.ok(productService.save(product));
}
    

If invalid data is sent, the global exception handler returns a structured error response.

  • Always validate input data using annotations like @NotNull, @Size, @Email, and @Pattern to ensure integrity.
  • Use DTOs (Data Transfer Objects) for validation rather than exposing entity classes directly.
  • Centralize exception handling with @ControllerAdvice for consistency across all controllers.
  • Return meaningful error messages in a structured format (JSON) so clients can parse them easily.
  • Use proper HTTP status codes: 400 for validation errors, 404 for not found, 500 for server errors.
  • Log exceptions with sufficient context for debugging and monitoring, but avoid exposing sensitive details to clients.
  • Implement custom exceptions for domain-specific errors (e.g., ResourceNotFoundException, InvalidPaymentException).
  • Adopt standardized error response formats like RFC 7807 (Problem Details for HTTP APIs).
  • Externalize validation messages for internationalization and localization support.
  • Test validation and exception handling thoroughly with unit and integration tests.
  • Diagram: Best Practices Flow

    Input Validation → DTO Layer → Controller → Global Exception Handler → Structured Error Response → Client

    8. Common Mistakes

    • Skipping validation entirely, leading to inconsistent or insecure data.
    • Returning raw stack traces to clients, exposing sensitive information.
    • Mixing business logic with exception handling inside controllers.
    • Using incorrect HTTP status codes (e.g., returning 200 OK for errors).
    • Not handling validation errors globally, resulting in inconsistent responses.
    • Hardcoding error messages instead of externalizing them for localization.
    • Failing to log exceptions, making debugging difficult.
    • Ignoring nested object validation, leading to incomplete checks.
    Diagram: Pitfalls

    Invalid Input → No Validation → Runtime Error → Raw Exception → Poor Client Experience

    9. Interview Notes

    • Be ready to explain how @Valid triggers validation in Spring MVC.
    • Discuss common validation annotations and their use cases.
    • Explain the role of @ControllerAdvice and @ExceptionHandler in global error handling.
    • Know how to return structured error responses with proper HTTP status codes.
    • Understand advanced validation techniques like custom validators and validation groups.
    • Be able to describe best practices for logging and monitoring exceptions.
    • Discuss standardized error formats like RFC 7807 and why they matter.
    Diagram: Interview Prep Map

    Validation Basics → Advanced Validation → Exception Handling Basics → Advanced Exception Handling → Best Practices → Common Mistakes

    10. Final Mastery Summary

    Validation and Exception Handling are essential for building robust REST APIs. Validation ensures data integrity by enforcing rules on incoming requests, while exception handling ensures errors are communicated clearly and consistently to clients. Together, they form the backbone of reliable, secure, and user-friendly APIs.

    By mastering validation annotations, advanced techniques like custom validators, global exception handling with @ControllerAdvice, structured error responses, and best practices, developers can build APIs that are production-ready and scalable. Avoiding common mistakes ensures that APIs remain secure and maintainable.

    For interviews, emphasize your understanding of validation flow, exception handling mechanisms, best practices, and pitfalls. Demonstrating mastery of these concepts shows readiness for backend engineering, microservices architecture, and enterprise application development roles.

    Diagram: Mastery Roadmap

    Validation → Exception Handling → Best Practices → Testing → Deployment → Mastery