Hello! Let's dive into our next lesson.
In our last session, you successfully implemented server-side validation using annotations like @NotBlank and @Size. We saw how adding @Valid to a controller method protects our application from malformed data. However, we were left with a problem: when validation fails, Spring's default error response is verbose, exposes internal details, and is difficult for a client application to work with.
Today, we will solve that. This lesson focuses on the learning outcome: Implement a global exception handler using @ControllerAdvice to create consistent JSON error responses.
We will intercept exceptions across our entire application and transform them into a clean, predictable, and professional API error contract. This is a cornerstone of building robust, production-grade REST APIs.
MERN vs. Spring Boot: Centralized Error Handling
In your experience with Node.js and Express, you've likely used a dedicated error-handling middleware. This is typically a function with the signature (err, req, res, next) placed at the very end of your middleware stack. Inside this function, you'd use if/else or switch statements to check the type of err and craft an appropriate JSON response.
// A typical Express error handler
app.use((err, req, res, next) => {
console.error(err.stack);
if (err.name === 'ValidationError') {
return res.status(400).json({ message: err.message });
}
if (err.name === 'UnauthorizedError') {
return res.status(401).json({ message: 'Invalid token' });
}
return res.status(500).json({ message: 'Something went wrong' });
});
Spring provides a more elegant and powerful mechanism for this same pattern: @ControllerAdvice. A class annotated with @ControllerAdvice (or more specifically for REST, @RestControllerAdvice) acts as a global interceptor for exceptions thrown from any of your @RestController classes. Inside this "advice" class, you define methods annotated with @ExceptionHandler to handle specific exception types, much like the if blocks in the Express example.
The Goal: A Clean and Consistent Error Flow
Our objective is to intercept exceptions before they result in the default error page and instead return a structured JSON response.

Step 1: Defining the API Error Contract
First, let's define the structure of our JSON error response. A good error contract is predictable and provides just enough information. We'll need a main error response object and a sub-object for field-specific validation errors. Using Java records is a modern and concise way to create these immutable data carriers.
-
Create a new package named
com.example.blogplatform.exception. -
Inside this package, create a new file
ApiErrorResponse.java:package com.example.blogplatform.exception; import com.fasterxml.jackson.annotation.JsonInclude; import java.time.LocalDateTime; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) // Don't include null fields in the JSON public record ApiErrorResponse( String message, int status, LocalDateTime timestamp, List<ApiValidationError> fieldErrors ) { } -
Next, create the
ApiValidationError.javarecord in the same package. This will hold details for each field that fails validation.package com.example.blogplatform.exception; public record ApiValidationError( String field, String message ) { }
This structure is a common pattern and provides a clear contract for any client consuming your API.
Step 2: Implementing the Global Exception Handler
Now we'll create the central component that uses this structure. This class will listen for exceptions across the application.
Let's watch a short video that brilliantly explains the motivation for moving from scattered try-catch blocks to a centralized @ControllerAdvice.
Master Exception Handling in Spring Boot: @ExceptionHandler & @ControllerAdvice Explained
The video 'Master Exception Handling in Spring Boot' by CodeSnippet clearly demonstrates the problem with handling exceptions in each controller and introduces @ControllerAdvice as the solution for centralizing this logic.
Please watch from 06:49 to 22:36. The key progression to focus on is: The Problem (06:49 - 13:32): Shows why try-catch in every controller method is repetitive and unmaintainable. A Better Way (13:32 - 18:23): Introduces @ExceptionHandler to handle exceptions within a single controller. The Global Solution (18:23 - 22:36): Finally, it introduces @ControllerAdvice to handle exceptions across ALL controllers, which is exactly what we need.
Now, let's implement this.
-
Create a new class named
GlobalExceptionHandler.javain thecom.example.blogplatform.exceptionpackage. -
Annotate the class with
@RestControllerAdvice.@RestControllerAdvicevs.@ControllerAdvice: The@RestControllerAdviceannotation is a specialization of@ControllerAdviceused for REST APIs. It combines@ControllerAdviceand@ResponseBody, which means the return value of its methods will be automatically serialized into the response body (e.g., as JSON), saving us from having to wrap every return type in aResponseEntity. You can read more about this distinction in the Jose López article "Global Exception Handling in Spring Boot".
Your initial class should look like this:
package com.example.blogplatform.exception;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
// We will add handler methods here
}
Step 3: Handling Validation Errors (MethodArgumentNotValidException)
Our first task is to handle the MethodArgumentNotValidException that we saw in the previous lesson. We'll create a method that specifically catches this exception and transforms it into our ApiErrorResponse.
The following video provides a step-by-step guide to do exactly this.
Spring Boot | REST API Request Validation & Exception Handling Realtime Example | JavaTechie
The video 'REST API Request Validation & Exception Handling' by Java Techie provides a perfect real-time demonstration of creating a handler for MethodArgumentNotValidException.
Please watch from 21:41 to 28:29. Pay close attention to these key actions: Creating the handler class with @RestControllerAdvice. Defining a method annotated with @ExceptionHandler(MethodArgumentNotValidException.class). Accessing the validation errors via exception.getBindingResult().getFieldErrors(). Looping through the errors to extract the field name and default message. Building a structured map (we'll use our DTO) and returning it with a 400 Bad Request status.
Now, add the following method to your GlobalExceptionHandler.java:
package com.example.blogplatform.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse handleValidationExceptions(MethodArgumentNotValidException ex) {
List<ApiValidationError> validationErrors = ex.getBindingResult().getFieldErrors().stream()
.map(error -> new ApiValidationError(error.getField(), error.getDefaultMessage()))
.collect(Collectors.toList());
return new ApiErrorResponse(
"Validation failed",
HttpStatus.BAD_REQUEST.value(),
LocalDateTime.now(),
validationErrors
);
}
}
Code Breakdown:
@ExceptionHandler(MethodArgumentNotValidException.class): This annotation registers this method as the handler for this specific exception.@ResponseStatus(HttpStatus.BAD_REQUEST): This conveniently sets the HTTP response status code to 400.ex.getBindingResult().getFieldErrors(): This is the crucial part. We get the results of the validation and extract a list of all the fields that failed..stream().map(...): We use a Java Stream to iterate over eachFieldErrorand map it to our customApiValidationErrorrecord. This is analogous to usingarray.map()in JavaScript.new ApiErrorResponse(...): We construct our final, clean error object.
Runtime Observation & Debugging
Time to see our work in action.
-
Run your application.
-
Using Postman or
curl, send the same invalidPOSTrequest tohttp://localhost:8080/api/poststhat you used in the last lesson (e.g., with a blank title).Body:
{ "title": " ", "content": "This content is fine, but the title is not." } -
Observe the new response! Instead of the messy default Spring error, you should now get a clean, structured JSON response:
{ "message": "Validation failed", "status": 400, "timestamp": "2024-08-10T14:30:00.123456", "fieldErrors": [ { "field": "title", "message": "Title cannot be blank" }, { "field": "title", "message": "Title must be between 3 and 255 characters" } ] }(Note: Your timestamp will vary, and you might see multiple messages for the same field if it violates multiple rules.)
Debugging Task:
Place a breakpoint on the first line inside your handleValidationExceptions method. Rerun the invalid request in debug mode. When the code execution pauses, inspect the ex (MethodArgumentNotValidException) object. Navigate through its fields to find bindingResult and then fieldErrors. You'll see firsthand how Spring packages the validation failure information for you to use.
Step 4: Handling Custom Business Exceptions
A global handler isn't just for validation. It's for any exception you want to handle consistently. A very common case is a "resource not found" error.
Let's implement this for fetching a post by an ID that doesn't exist.
-
Create a custom exception: In the
exceptionpackage, create a new classResourceNotFoundException.java.package com.example.blogplatform.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) // This directly sets the response status public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }By extending
RuntimeException, we create an "unchecked" exception, which, like in JavaScript/TypeScript, doesn't need to be explicitly declared withthrowsin every method signature. -
Throw the exception from your Service: In
PostService.java, modify thegetPostByIdmethod (which you created in a previous lesson) to throw this exception.// In PostService.java import com.example.blogplatform.exception.ResourceNotFoundException; public PostDTO getPostById(Long id) { return postRepository.findById(id) .map(postMapper::toDTO) .orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + id)); } -
Add a handler method: Now, add a new handler to
GlobalExceptionHandler.javafor our custom exception.// In GlobalExceptionHandler.java import com.example.blogplatform.exception.ResourceNotFoundException; // ... other imports @RestControllerAdvice public class GlobalExceptionHandler { // ... existing handleValidationExceptions method ... @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ApiErrorResponse handleResourceNotFoundException(ResourceNotFoundException ex) { return new ApiErrorResponse( ex.getMessage(), HttpStatus.NOT_FOUND.value(), LocalDateTime.now(), null // No field errors for this type of exception ); } }
Now, if you call GET /api/posts/999 (assuming 999 is a non-existent ID), the .orElseThrow() will trigger, your new handler will catch the ResourceNotFoundException, and you'll get a clean 404 Not Found response with your custom message.
Conclusion
Congratulations! You have now implemented a robust, centralized exception handling mechanism—a critical component of any professional backend service. You've replaced Spring Boot's default, developer-focused errors with a clean, predictable API contract for your clients.
Key Takeaways:
@RestControllerAdvicecreates a global interceptor for exceptions in your REST controllers.@ExceptionHandlermethods act as targeted handlers for specific exception types (e.g.,MethodArgumentNotValidException,ResourceNotFoundException).- Defining a consistent DTO for error responses (e.g.,
ApiErrorResponse) is a best practice for API design. - You can handle both built-in framework exceptions and your own custom business exceptions in the same centralized place.
We've now covered how to validate incoming data and how to handle errors gracefully. But what happens when an operation involves multiple steps, like updating a post and its associated tags? If the tag update fails, should the post update be undone?
Preview of the Next Lesson:
In our next lesson, we will explore @Transactional. You will learn how to use this powerful annotation to group multiple database operations into a single, atomic unit of work, ensuring that your data remains consistent even when things go wrong.