Popular Searches
Popular Course Categories
Popular Courses

Implementing Request Validation and Error Responses

Implementing Request Validation and Error Responses

RESTful Web Services and API Development

Implementing Request Validation and Error Responses in Spring Boot

Course: Advanced Java Training

Topic: Implementing Request Validation and Error Responses

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Request Validation and Error Responses

Request validation and error handling are essential parts of developing reliable REST APIs with Spring Boot. Request validation ensures that incoming data follows the required rules before the application processes it. Error handling ensures that clients receive meaningful and consistent responses when requests fail or unexpected problems occur.

For example, consider a user registration API. The application may require a valid email address, a non-empty username, and a password that satisfies specified length requirements. If a client submits invalid information, the API should reject the request and return an appropriate HTTP status code with useful error details.

Why Are Request Validation and Error Responses Important?

  • Prevent invalid or incomplete data from entering the application.
  • Improve data quality and business rule enforcement.
  • Provide clear feedback to frontend and mobile applications.
  • Reduce unexpected application failures.
  • Make REST APIs easier to debug and maintain.
  • Improve API security by avoiding unnecessary exposure of internal errors.

2. What Is Request Validation?

Request validation is the process of checking incoming data against predefined rules before using it in business logic or database operations.

Spring Boot commonly uses Jakarta Bean Validation annotations to define validation rules on Java classes and method parameters. The validation provider checks the annotated fields and reports violations when the supplied data does not satisfy the constraints.

Examples of Validation Rules

Field Validation Rule Example
Name Must not be blank "Rahul"
Email Must follow the expected email format "[email protected]"
Age Must be at least 18 25
Price Must be greater than zero 1499.00
Username Must contain an allowed number of characters "rahul123"
Password Must satisfy the defined length requirements A password meeting the policy

3. Setting Up Validation in Spring Boot

To use standard Jakarta Bean Validation annotations, add the Spring Boot validation starter to your Maven project.

Maven Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

This dependency provides integration with Bean Validation and a validation provider in a typical Spring Boot application.

For Spring Boot 3 and later, use the jakarta.validation package. Older Spring Boot 2 applications commonly use the javax.validation package, so the imports must match the application's version.

4. Common Validation Annotations

Jakarta Bean Validation provides annotations that define constraints on fields, method parameters, and other supported elements.

Annotation Purpose Example
@NotNull Rejects a null value @NotNull private Long id;
@NotBlank Rejects null, empty, or whitespace-only text @NotBlank private String name;
@NotEmpty Rejects null or empty strings and collections @NotEmpty private List<String> items;
@Size Restricts the size of a string, collection, or supported value @Size(min = 3, max = 30)
@Email Checks whether text has a valid email-like format @Email private String email;
@Min Sets a minimum numeric value @Min(18) private int age;
@Max Sets a maximum numeric value @Max(100) private int age;
@Positive Requires a positive numeric value @Positive private double price;
@PositiveOrZero Allows zero and positive numeric values @PositiveOrZero private int quantity;
@Pattern Validates text against a regular expression @Pattern(regexp = "^[A-Z]+$")

Important: @NotNull, @NotEmpty, and @NotBlank have different meanings. For example, @NotNull alone does not reject an empty string, while @NotBlank is designed for non-empty text containing at least one non-whitespace character.

5. Creating a Request DTO with Validation

A Data Transfer Object (DTO) defines the structure of data accepted by or returned from an API. Using a dedicated request DTO allows developers to apply validation rules without exposing internal database entities directly.

Example: User Registration Request

package com.example.demo.dto;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class UserRegistrationRequest {

    @NotBlank(message = "Name is required")
    @Size(min = 3, max = 50,
          message = "Name must contain between 3 and 50 characters")
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Please provide a valid email address")
    private String email;

    @NotBlank(message = "Password is required")
    @Size(min = 8, max = 100,
          message = "Password must contain between 8 and 100 characters")
    private String password;

    public UserRegistrationRequest() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Explanation

  • @NotBlank ensures that mandatory text fields are not blank.
  • @Size limits the accepted text length.
  • @Email checks the email's general format but does not confirm that the address exists.
  • The custom messages describe what the client needs to correct.

For production applications, passwords should be securely hashed before storage and must never be returned in API responses or written to logs.

6. Using @Valid in a REST Controller

The @Valid annotation instructs Spring to validate a supported request object against its declared constraints. When validation fails, Spring MVC typically raises a MethodArgumentNotValidException for an invalid request body.

Controller Example

package com.example.demo.controller;

import com.example.demo.dto.UserRegistrationRequest;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PostMapping("/register")
    public ResponseEntity<Map<String, String>> registerUser(
            @Valid @RequestBody UserRegistrationRequest request) {

        Map<String, String> response = Map.of(
            "message", "User registration request is valid",
            "name", request.getName()
        );

        return ResponseEntity
                .status(HttpStatus.CREATED)
                .body(response);
    }
}

This example validates the request before executing the controller method. It demonstrates request validation only; it does not create a user in a database.

Example Valid JSON Request

{
  "name": "Rahul Sharma",
  "email": "[email protected]",
  "password": "SecurePass123"
}

Example Invalid JSON Request

{
  "name": "",
  "email": "invalid-email",
  "password": "123"
}

The invalid request violates the name, email, and password constraints. The application should return a client error response containing understandable validation messages.

7. Understanding Error Responses in REST APIs

An error response communicates that a request could not be completed successfully. A well-designed API returns an appropriate HTTP status code and a response body that explains the problem without exposing sensitive internal information.

Common HTTP Error Status Codes

Status Code Name Meaning
400 Bad Request The request contains invalid input or fails validation.
401 Unauthorized Authentication is missing or invalid.
403 Forbidden The client is authenticated or identified but lacks permission.
404 Not Found The requested resource does not exist.
405 Method Not Allowed The endpoint does not support the requested HTTP method.
409 Conflict The request conflicts with the current resource state, such as a duplicate record.
415 Unsupported Media Type The request body format is not supported.
422 Unprocessable Content The content is understood but cannot be processed according to the application's rules.
500 Internal Server Error An unexpected server-side problem occurred.

Use status codes consistently. For example, invalid request data generally results in HTTP 400, while a missing resource generally results in HTTP 404. The precise status code for a business rule violation should follow the API's documented error contract.

8. Creating a Custom Error Response Structure

A custom error response provides a consistent format for API failures. Rather than returning unrelated messages from different controllers, the application can use a common structure containing the timestamp, status code, error description, request path, and field-level validation messages.

Example Error Response

{
  "timestamp": "2026-10-24T10:30:00",
  "status": 400,
  "error": "Validation Failed",
  "message": "One or more fields contain invalid values",
  "path": "/api/users/register",
  "fieldErrors": {
    "name": "Name is required",
    "email": "Please provide a valid email address",
    "password": "Password must contain between 8 and 100 characters"
  }
}

The values above are illustrative. Your application should generate the timestamp, status, path, and validation messages dynamically from the actual request and exception.

Creating an Error Response DTO

package com.example.demo.dto;

import java.time.LocalDateTime;
import java.util.Map;

public class ApiErrorResponse {

    private LocalDateTime timestamp;
    private int status;
    private String error;
    private String message;
    private String path;
    private Map<String, String> fieldErrors;

    public ApiErrorResponse() {
    }

    public ApiErrorResponse(
            LocalDateTime timestamp,
            int status,
            String error,
            String message,
            String path,
            Map<String, String> fieldErrors) {
        this.timestamp = timestamp;
        this.status = status;
        this.error = error;
        this.message = message;
        this.path = path;
        this.fieldErrors = fieldErrors;
    }

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public int getStatus() {
        return status;
    }

    public String getError() {
        return error;
    }

    public String getMessage() {
        return message;
    }

    public String getPath() {
        return path;
    }

    public Map<String, String> getFieldErrors() {
        return fieldErrors;
    }
}

This DTO defines a reusable response structure. The application can populate it whenever request validation or another handled error occurs.

9. Handling Validation Errors with @RestControllerAdvice

The @RestControllerAdvice annotation enables centralized exception handling across REST controllers. Combined with @ExceptionHandler, it allows the application to return consistent error responses without repeating error-handling code in every controller.

Global Validation Exception Handler

package com.example.demo.exception;

import com.example.demo.dto.ApiErrorResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiErrorResponse> handleValidationErrors(
            MethodArgumentNotValidException ex,
            HttpServletRequest request) {

        Map<String, String> fieldErrors = new LinkedHashMap<>();

        ex.getBindingResult().getFieldErrors().forEach(error ->
            fieldErrors.putIfAbsent(
                error.getField(),
                error.getDefaultMessage()
            )
        );

        ApiErrorResponse response = new ApiErrorResponse(
            LocalDateTime.now(),
            HttpStatus.BAD_REQUEST.value(),
            "Validation Failed",
            "One or more fields contain invalid values",
            request.getRequestURI(),
            fieldErrors
        );

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(response);
    }
}

How This Handler Works

  1. @RestControllerAdvice makes the handler available across REST controllers.
  2. @ExceptionHandler(MethodArgumentNotValidException.class) handles validation errors raised for invalid request objects.
  3. The field errors are extracted from the binding result.
  4. putIfAbsent() retains the first message for each field if multiple constraints fail on that field.
  5. An ApiErrorResponse object is created with the error details.
  6. ResponseEntity returns the response with HTTP 400 Bad Request.

This handler covers request-object validation errors. Other failures, such as malformed JSON or direct method-parameter constraint violations, may raise different exceptions and should be handled separately when the application requires a consistent response for them.

10. Handling Resource Not Found Errors

In REST APIs, a resource-not-found error occurs when a client requests a record that does not exist. For example, requesting a user with ID 500 when no such user exists should normally result in HTTP 404 Not Found.

Creating a Custom Exception

package com.example.demo.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

Adding a Handler to GlobalExceptionHandler

import com.example.demo.exception.ResourceNotFoundException;
import jakarta.servlet.http.HttpServletRequest;

// Add this method inside GlobalExceptionHandler.

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiErrorResponse> handleNotFound(
        ResourceNotFoundException ex,
        HttpServletRequest request) {

    ApiErrorResponse response = new ApiErrorResponse(
        LocalDateTime.now(),
        HttpStatus.NOT_FOUND.value(),
        "Resource Not Found",
        ex.getMessage(),
        request.getRequestURI(),
        Map.of()
    );

    return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(response);
}

Example Usage in a Controller

@GetMapping("/{id}")
public String getUser(@PathVariable Long id) {
    if (id != 1L) {
        throw new ResourceNotFoundException(
            "User not found with ID: " + id
        );
    }

    return "User found";
}

This simplified example uses a fixed ID for demonstration. In a real application, the controller should call a service that retrieves the user from the repository and throws the exception when the requested record is absent.

11. Handling Malformed JSON Requests

Malformed JSON occurs when the request body cannot be parsed into the expected Java object. For example, a missing quotation mark or an invalid value type may prevent Spring from deserializing the request.

Example Invalid JSON

{
  "name": "Rahul",
  "email": "[email protected]",
  "age": "twenty-five"
}

If the target Java property expects a number, the string value shown above may cause a message-conversion error.

Handling Malformed JSON

import com.example.demo.dto.ApiErrorResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;

// Add this method inside GlobalExceptionHandler.

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ApiErrorResponse> handleMalformedJson(
        HttpMessageNotReadableException ex,
        HttpServletRequest request) {

    ApiErrorResponse response = new ApiErrorResponse(
        LocalDateTime.now(),
        HttpStatus.BAD_REQUEST.value(),
        "Malformed Request",
        "The request body is missing, invalid, or contains unsupported values",
        request.getRequestURI(),
        Map.of()
    );

    return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .body(response);
}

Keep the client-facing message generic. Detailed parser exceptions may reveal implementation information and are usually more appropriate for protected server-side logs.

12. Handling Duplicate Records and Business Errors

Some requests are syntactically valid but violate application rules. For example, registering an email address that already exists may create a conflict with the current application state.

HTTP 409 Conflict is often appropriate for duplicate-resource situations. The exact response should follow the API's documented behavior.

Example Custom Business Exception

package com.example.demo.exception;

public class DuplicateResourceException extends RuntimeException {

    public DuplicateResourceException(String message) {
        super(message);
    }
}

Handler Example

import com.example.demo.exception.DuplicateResourceException;

// Add this method inside GlobalExceptionHandler.

@ExceptionHandler(DuplicateResourceException.class)
public ResponseEntity<ApiErrorResponse> handleDuplicateResource(
        DuplicateResourceException ex,
        HttpServletRequest request) {

    ApiErrorResponse response = new ApiErrorResponse(
        LocalDateTime.now(),
        HttpStatus.CONFLICT.value(),
        "Resource Conflict",
        ex.getMessage(),
        request.getRequestURI(),
        Map.of()
    );

    return ResponseEntity
            .status(HttpStatus.CONFLICT)
            .body(response);
}

The service layer should check relevant business rules and throw the appropriate exception. Database constraints should also protect important uniqueness requirements against concurrent requests.

13. Validating Query Parameters and Path Variables

Validation is not limited to JSON request bodies. Query parameters and path variables can also be constrained when their values affect application behavior.

Example

import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
@Validated
public class ProductSearchController {

    @GetMapping("/search")
    public String searchProducts(
            @RequestParam
            @Min(value = 1, message = "Page must be at least 1")
            int page) {

        return "Searching page " + page;
    }
}

Method-parameter validation support depends on the Spring Framework version and method signature. With Spring Framework 6.1 and later, Spring MVC has built-in method validation support; class-level @Validated invokes method validation through an AOP proxy instead. Choose the approach appropriate for the application version.

Depending on the validation path, failures may produce HandlerMethodValidationException or ConstraintViolationException. Add handlers for the exceptions relevant to your controller configuration if consistent error formatting is required.

14. Handling Multiple Validation Exceptions

Different validation scenarios can produce different exceptions. A robust API should understand these differences instead of assuming every validation failure raises the same exception.

Exception Typical Cause Suggested Handling
MethodArgumentNotValidException An object such as a validated request DTO fails validation. Extract field errors and return HTTP 400.
HandlerMethodValidationException Controller method parameter or return-value validation fails under Spring MVC method validation. Extract parameter validation results and return an appropriate client or server error.
ConstraintViolationException Bean Validation constraints fail in method or service validation paths. Handle according to the operation and API contract.
HttpMessageNotReadableException Request body is missing, malformed, or cannot be converted. Return a clear HTTP 400 response.
ResourceNotFoundException An application-specific resource lookup fails. Return HTTP 404.

When extending Spring's exception-handling infrastructure, avoid adding duplicate or conflicting handlers for the same exception. If you extend ResponseEntityExceptionHandler, customize its supported methods as appropriate for the Spring version.

15. Using ProblemDetail for Standardized Error Responses

Spring Framework 6 and later support ProblemDetail, which provides a standard structure for HTTP API error responses based on RFC 9457. It can be useful when an application wants to follow a standardized problem-details format instead of defining every error field from scratch.

Example

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ProblemController {

    @GetMapping("/problem")
    public String demonstrateProblem() {
        throw new IllegalArgumentException(
            "The requested operation is not valid"
        );
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ProblemDetail handleIllegalArgument(
            IllegalArgumentException ex) {

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST,
            ex.getMessage()
        );

        problem.setTitle("Invalid Request");
        problem.setProperty("errorCode", "INVALID_REQUEST");

        return problem;
    }
}

The example demonstrates local exception handling within a controller. For application-wide handling, move the handler to a class annotated with @RestControllerAdvice. Spring can serialize the result using the problem-details media type when supported and negotiated.

For Spring Boot applications, problem-details handling can also be enabled using the appropriate configuration property for the Spring Boot version in use. Review the framework documentation before combining built-in problem-details handling with custom advice.

16. Testing Validation and Error Responses

Testing verifies that invalid requests are rejected and that clients receive the correct status code and response format. Both positive and negative test cases should be included.

Testing with Postman

  1. Start the Spring Boot application.
  2. Open Postman and select POST.
  3. Enter http://localhost:8080/api/users/register.
  4. Select Body, then raw, then JSON.
  5. Submit a valid request and verify the expected success response.
  6. Submit invalid values, such as a blank name or malformed email.
  7. Verify that the API returns HTTP 400 and the expected validation messages.
  8. Test malformed JSON and missing resources separately.

Automated Test Example

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(UserController.class)
class UserControllerValidationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void shouldRejectInvalidRegistrationRequest() throws Exception {
        String invalidJson = """
            {
              "name": "",
              "email": "invalid-email",
              "password": "123"
            }
            """;

        mockMvc.perform(post("/api/users/register")
                .contentType(MediaType.APPLICATION_JSON)
                .content(invalidJson))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.status").value(400))
                .andExpect(jsonPath("$.error")
                    .value("Validation Failed"))
                .andExpect(jsonPath("$.fieldErrors.name").exists());
    }
}

This test assumes that the global exception handler is included in the web test application context and that the controller and DTO classes match the examples above. Depending on the project's package structure, you may need to import the advice explicitly.

17. Common Validation and Error-Handling Mistakes

Mistake Why It Is a Problem Recommended Solution
Forgetting @Valid Request-object constraints may not be triggered. Add @Valid to supported request parameters.
Missing validation dependency Validation annotations may not be processed by a provider. Add the validation starter.
Using @NotNull for non-empty text An empty string may still be accepted. Use @NotBlank where appropriate.
Returning HTTP 200 for every error Clients cannot reliably determine the result. Return an appropriate HTTP status code.
Repeating exception logic in every controller Code becomes duplicated and inconsistent. Use centralized exception handling.
Exposing stack traces in responses Internal details may leak to clients. Return safe error messages and log details securely.
Validating only in the frontend API requests can bypass browser validation. Enforce validation on the server.
Assuming email validation verifies existence Format checks do not prove an inbox exists. Use a verification workflow when required.
Ignoring database constraints Concurrent requests can bypass application-only checks. Use database constraints for critical integrity rules.

18. Best Practices for Request Validation

  • Use dedicated request DTOs for incoming data.
  • Apply the most appropriate validation annotation to each field.
  • Use custom messages that explain how to correct invalid input.
  • Validate requests on the server even when frontend validation exists.
  • Apply business rules in the service layer when they depend on application state.
  • Use global exception handling for consistent responses.
  • Return the correct HTTP status code for each category of failure.
  • Avoid including passwords, tokens, database details, or stack traces in responses.
  • Write automated tests for valid data, invalid data, and boundary values.
  • Document the error response structure so API consumers can handle it reliably.

19. Practical Project: User Registration API

Create a user registration REST API that validates incoming data and returns structured error responses whenever a request fails.

Project Requirements

  • Create a UserRegistrationRequest DTO.
  • Validate the name, email, and password fields.
  • Create a controller endpoint at POST /api/users/register.
  • Use @Valid to activate request validation.
  • Create an ApiErrorResponse DTO for consistent errors.
  • Implement a @RestControllerAdvice class.
  • Handle validation errors and malformed JSON.
  • Return HTTP 404 for missing resources and HTTP 409 for applicable duplicate-resource conflicts.
  • Test success and failure scenarios using Postman and MockMvc.
  • Optionally integrate the application with Spring Data JPA and a database.

Expected Behavior

Scenario Expected Status Expected Result
All fields are valid 201 Created Registration request accepted or resource created, according to implementation.
Name is blank 400 Bad Request Field validation error returned.
Email format is invalid 400 Bad Request Email validation error returned.
Password is too short 400 Bad Request Password validation error returned.
Request JSON is malformed 400 Bad Request Safe request-format error returned.
Requested user does not exist 404 Not Found Resource-not-found error returned.
Email already exists 409 Conflict Duplicate-resource error returned, if this is the API's chosen contract.

20. Interview Questions and Answers

Q1. What is request validation in Spring Boot?

Answer: Request validation checks incoming data against predefined constraints before it is processed by the application. Spring commonly uses Jakarta Bean Validation annotations to define these rules.

Q2. What is the purpose of @Valid?

Answer: @Valid instructs Spring to validate a supported object parameter, such as a request DTO, against its declared constraints.

Q3. What is the difference between @NotNull and @NotBlank?

Answer: @NotNull rejects null values. @NotBlank rejects null, empty, and whitespace-only character sequences.

Q4. What is @RestControllerAdvice?

Answer: It provides centralized exception handling for REST controllers and writes handler return values directly into response bodies.

Q5. What is MethodArgumentNotValidException?

Answer: It is commonly raised when an individual request object, such as a validated JSON request DTO, fails Spring MVC validation.

Q6. Why should APIs return meaningful error messages?

Answer: Clear error responses help clients identify invalid fields, correct requests, and handle failures consistently without exposing sensitive internal information.

Q7. What is the purpose of ResponseEntity?

Answer: ResponseEntity allows a controller or exception handler to set the HTTP status code, headers, and response body.

Q8. What is the difference between HTTP 400 and HTTP 500?

Answer: HTTP 400 generally indicates a client request problem, while HTTP 500 indicates an unexpected server-side failure.

Q9. How do you handle a resource-not-found error?

Answer: Create an application-specific exception and handle it centrally to return HTTP 404 with a structured error response.

Q10. What is ProblemDetail?

Answer: ProblemDetail is a Spring Framework representation for standardized HTTP API error responses based on RFC 9457.

21. Practice Exercises

  1. Create a DTO with name, email, age, and password fields.
  2. Apply suitable validation annotations to every field.
  3. Create a POST endpoint that validates the DTO.
  4. Return field-specific validation messages.
  5. Create a global exception handler using @RestControllerAdvice.
  6. Handle malformed JSON requests with HTTP 400.
  7. Create a custom resource-not-found exception and return HTTP 404.
  8. Implement duplicate-email handling using HTTP 409.
  9. Write MockMvc tests for valid and invalid requests.
  10. Document your API's status codes and error response structure.

22. Quick Revision Checklist

  • spring-boot-starter-validation provides validation integration.
  • @NotBlank rejects blank text.
  • @Email checks the general email format.
  • @Size restricts the size of supported values.
  • @Valid triggers validation for supported request objects.
  • @RestControllerAdvice centralizes REST exception handling.
  • @ExceptionHandler maps exceptions to handler methods.
  • ResponseEntity controls HTTP response status, headers, and body.
  • HTTP 400 is commonly used for invalid requests.
  • HTTP 404 indicates a missing resource.
  • HTTP 409 can represent a resource conflict.
  • HTTP 500 indicates an unexpected server-side failure.
  • ProblemDetail supports standardized problem responses.
  • Postman and MockMvc help test validation and error handling.

Conclusion

Implementing request validation and structured error responses is an important part of building dependable Spring Boot REST APIs. By using Jakarta Bean Validation, @Valid, custom error DTOs, @RestControllerAdvice, and appropriate HTTP status codes, developers can reject invalid requests consistently and provide useful feedback to API consumers.

Explore additional backend development concepts through the Advanced Java Training course at JustAcademy. You can also register for a course demo or visit the JustAcademy official website.

Official Documentation

Previous Next
whatsapp