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);
}
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
ConstraintValidatorfor 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 extends Payload>[] 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
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.
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.
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.
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.
Validation → Exception Handling → Best Practices → Testing → Deployment → Mastery