Learning Outcome
5
Implement global exception handling for REST APIs
4
Differentiate types of exceptions in Java clearly
3
Create custom validation for specific business rules
2
Apply validation annotations in Spring Boot applications
1
Understand DTO usage for secure data transfer
DTO (Data Transfer Object) is a simple Java class used to transfer data between different layers of an application.
EmployeeDTO.java
public class EmployeeDTO {
private String name;
private String department;
// Getters & Setters
}
Simple POJO with only the fields needed for data transfer
Key Features
Lightweight
Contains only essential fields
Serializable
Easy to serialize for APIs
Encapsulated
Private fields with accessors
Validation is the process of checking whether the input data is correct, complete, and follows required rules before processing or storing it in the system.
User Input
Validate
Process
Ensures only correct data is stored in the database.
Prevents runtime issues caused by bad input.
Provides clear error messages for incorrect input.
To enable validation in Spring Boot, we add:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation
</artifactId>
</dependency>
Without this dependency, validation annotations will not work
Adds Hibernate Validator
Enables validation annotations
Integrates with Spring Boot
Bean Validation is a standard framework (API) used in Java to validate object fields (beans) using annotations.
Common annotations
@NotNull
Must not be null
@NotBlank
No empty or whitespace
@Min / @Max
Numeric range validation
@Size
String length validation
Common Use Cases
Form validation in web apps
API request validation
Data integrity enforcement
Custom validations are user-defined validation rules created when built-in annotations are not sufficient.
@Documented
Includes annotation in JavaDocs
@Constraint
Links to validation logic
@Target
Where annotation is used
@Retention
How long annotation is available
message()
Defines validation error message
groups()
Groups validations logically
payload() :
Carries custom metadata information
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = PasswordValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPassword {
String message() default "Invalid password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Exception Handling is a mechanism used to handle errors in an application so that it does not crash.
It ensures that errors result in meaningful responses rather than abrupt failures.
Graceful error handling improves user experience and system reliability
Ensures API continues running even when errors occur
Helps identify and fix issues quickly
Returns clear responses like "Employee not found"
Checked Exceptions
Checked at compile time
Must be handled using try-catch or throws
Unchecked Exceptions
Occur at runtime
Not checked at compile time
Custom Exceptions
User-defined exceptions
Created to handle specific business logic errors
When an exception occurs in a Spring Boot application and no custom handling is defined, Spring Boot automatically returns a default error response.
{
"timestamp": "2026-03-26T10:30:00.123+00:00",
"status": 404,
"error": "Not Found",
"message": "Employee not found",
"path": "/employees/1"
}
Time when the error occurred
HTTP status code (e.g., 404, 500)
Type of error (e.g., Not Found)
Error message describing the issue
API endpoint where the error occurred
Global Exception Handling is a way to handle all exceptions in one place instead of writing try-catch blocks in every controller.
Avoid repetitive try-catch blocks
Handle all exceptions in a single class
Return consistent error responses
Improve code readability and maintainability
@RestControllerAdvice
Used to create a global exception handler class
@ExceptionHandler
Used to handle specific exceptions
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
Custom Exception Class
Global Exception Handler
Summary
5
Global exception handling centralizes error response management
4
Custom validation handles complex business-specific rules
3
Bean Validation uses annotations for field rules
2
Validation ensures correct and meaningful input data
1
DTO transfers limited data between application layers
Quiz
Which annotation is used for global exception handling in Spring Boot?
A. @Controller
B. @RestControllerAdvice
C. @Component
D. @Service
Which annotation is used for global exception handling in Spring Boot?
A. @Controller
B. @RestControllerAdvice
C. @Component
D. @Service
Quiz-Answer