Advance Spring data JPA and production ready Rest APi

Validation & Exception Handling in APIs

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

What is DTO ?

DTO (Data Transfer Object) is a simple Java class used to transfer data between different layers of an application.

Purpose of DTO

Avoid exposing Entity directly to client

Transfer only necessary data

Customize API request and response

DTO Example

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 in Spring Boot

What is Validation?

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

Why use Validations ?

Ensures only correct data is stored in the database.

Prevents runtime issues caused by bad input.

Provides clear error messages for incorrect input.

Maven Dependency Setup

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

What This Does

Adds Hibernate Validator

Enables validation annotations

Integrates with Spring Boot

What is Bean Validation?

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

What are Custom Validations?

Custom validations are user-defined validation rules created when built-in annotations are not sufficient.

Common Use Cases

Email domain validation (company emails only)

Phone number format validation

Age restrictions based on business rules

Unique username validation

Custom validation annotations and attributes

@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

Example: @ValidPassword

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

Exception Handling is a mechanism used to handle errors in an application so that it does not crash.

Why Needed in REST APIs?

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

  • Occur due to external factors

Unchecked Exceptions

  • Occur at runtime

  • Not checked at compile time

  • Usually caused by programming mistakes

Custom Exceptions

  • User-defined exceptions

  • Created to handle specific business logic errors

  • Inherit from Exception class

Types of Exceptions

Default Spring Boot Error Response

When an exception occurs in a Spring Boot application and no custom handling is defined, Spring Boot automatically returns a default error response.

 

Example 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

Global Exception Handling is a way to handle all exceptions in one place instead of writing try-catch blocks in every controller.

Why Use Global Exception Handling?

Avoid repetitive try-catch blocks

Handle all exceptions in a single class

Return consistent error responses

Improve code readability and maintainability

Key annotations

@RestControllerAdvice

Used to create a global exception handler class

@ExceptionHandler

Used to handle specific exceptions

Example :

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