Hello! Welcome back to the course.
In our last lesson, we mastered creating custom validation annotations. We built @ValidSlug to enforce a specific business rule for our blog post slugs, ensuring they are clean and SEO-friendly. We saw how our existing @ControllerAdvice seamlessly handled these new validation failures, returning a structured 400 Bad Request response.
This is great, but our error handling is still incomplete. Right now, every error looks like a validation error to our system. What happens if a user tries to fetch a post that doesn't exist? Or tries to publish a post that's already been published? These aren't validation failures; they are application state failures. Treating them the same way—by returning a generic error or the wrong HTTP status—leads to a confusing and poorly designed API.
This brings us to today's crucial learning outcome: Distinguish between application-level exceptions and validation exceptions and handle each accordingly. We will evolve our GlobalExceptionHandler from a single-purpose tool into a sophisticated, centralized hub that can intercept different categories of errors and translate them into meaningful, precise HTTP responses.
Two Families of Exceptions in an API
In a typical REST API, most errors fall into two categories. Understanding this distinction is fundamental to good API design.
-
Validation Exceptions:
- Cause: The client sends data that violates the API's contract. The input is syntactically or semantically incorrect.
- Examples: A required field is missing (
@NotNull), an email format is wrong (@Email), or our custom@ValidSlugrule fails. - Who throws it?: The framework, typically triggered by
@Valid. The exception is usuallyMethodArgumentNotValidException. - HTTP Status:
400 Bad Request. The client made a mistake and needs to fix the request. - MERN Comparison: This is the direct equivalent of a
ZodorJoischema validation failing in your Express route handler. The request payload is invalid.
-
Application (or Business Logic) Exceptions:
- Cause: The request is valid, but it cannot be processed due to the current state of the application's business logic.
- Examples:
ResourceNotFoundException(fetching a post with a non-existent ID),EmailAlreadyInUseException(registering with a duplicate email),PostAlreadyPublishedException. - Who throws it?: You! The developer. You must
throwthese exceptions manually from your service layer when a business rule is violated. - HTTP Status: Varies depending on the context:
404 Not Found,409 Conflict,403 Forbidden, etc. - MERN Comparison: This is like your Node.js service logic finding that a user doesn't exist and doing
throw new NotFoundError('User not found'). An error-handling middleware then catches this specific error type and sends back a 404 response.
The following discussion on StackExchange reinforces a key architectural principle: your service layer should not know anything about HTTP. It should throw exceptions that describe a business problem (e.g., UserNotFound), and the web layer (@ControllerAdvice) is responsible for translating that into an HTTP response.
Where would you handle exceptions: controller, service, repository?
Please read this short but insightful StackExchange discussion. It perfectly articulates why we separate business exceptions from HTTP-specific error handling.
Focus on the top-voted answers. Note how they advocate for throwing business-level exceptions from the service layer and letting a global, transport-aware handler (like our @ControllerAdvice) translate them into HTTP statuses.
Implementing Differentiated Exception Handling
Let's put this into practice. We'll create a custom ResourceNotFoundException, throw it from our service when a post isn't found, and add a new handler for it in our @ControllerAdvice.
To see the end-to-end flow, watch this video. It demonstrates both handling validation exceptions (which we've done) and adding a handler for a custom UserNotFoundException, which is exactly what we're about to do.
Spring Boot | REST API Request Validation & Exception Handling Realtime Example | JavaTechie
This video from Java Techie provides a clear, practical example of handling both validation and business exceptions.
Watch from 22:47 to 26:47 to see how a MethodArgumentNotValidException is handled, which will be a quick review. Then, watch from 31:39 to 37:05. This part is key: observe how a custom UserNotFoundException is created, thrown from the service, and handled in the @RestControllerAdvice to return a specific error.
Now, let's apply these concepts to our blog platform. A professional way to structure this is to create a standard ErrorResponse DTO and a hierarchy of custom exceptions. The following article provides an excellent template for this.
How to Handle Exceptions Globally in Spring Boot
We will model our implementation based on the patterns in this excellent article from OneUptime. It showcases a production-grade approach to global exception handling.
First, read the section 'Standard Error Response' to understand the ErrorResponse DTO we'll be creating. Then, read 'Custom Exceptions' to see how to define a base ApplicationException and a specific ResourceNotFoundException. Finally, skim the GlobalExceptionHandler in the next section to see how it uses @ExceptionHandler to handle these different exception types. You don't need to read every handler, just focus on the ones for ApplicationException and MethodArgumentNotValidException to see the distinction.
Step 1: Create a Custom Application Exception
Following the pattern from the OneUptime article, let's create our own ResourceNotFoundException.
- Create a new package
com.example.blogplatform.exception. - Inside this package, create
ResourceNotFoundException.java. For now, we'll have it extendRuntimeException.
package com.example.blogplatform.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// The @ResponseStatus annotation is a simpler way to map an exception to an HTTP status.
// Spring will automatically use this status if the exception bubbles up to the response layer.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
Note on RuntimeException: In modern REST API development, we almost always extend RuntimeException (an unchecked exception). This avoids forcing every method in the call stack to declare throws ... in its signature, which keeps the code cleaner and is more aligned with how web request lifecycles work (an unhandled exception typically terminates the request anyway).
Step 2: Throw the Exception from the Service Layer
Now, let's modify a service method to throw this exception. A perfect candidate is finding a post by its ID.
In your PostService, update the getPostById method (or a similar method).
// In PostService.java
import com.example.blogplatform.exception.ResourceNotFoundException;
// ... other imports
@Service
public class PostService {
private final PostRepository postRepository;
// ... constructor
public PostResponseDto getPostById(Long id) {
Post post = postRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + id));
// Assuming you have a mapper to convert Post entity to PostResponseDto
return mapToPostResponseDto(post);
}
// ... other methods
}
The .orElseThrow() method from Optional is a clean and idiomatic way to handle cases where a database lookup returns nothing.
Step 3: Enhance the @ControllerAdvice
Our final step is to teach our GlobalExceptionHandler how to deal with ResourceNotFoundException. While @ResponseStatus on the exception class works, defining an explicit handler in @ControllerAdvice gives you more control to customize the response body.
First, let's define an ErrorResponse DTO in the com.example.blogplatform.exception package to standardize our error format.
// In ErrorResponse.java
import com.fasterxml.jackson.annotation.JsonInclude;
import java.time.Instant;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL) // Don't include null fields in JSON
public class ErrorResponse {
private final Instant timestamp;
private final int status;
private final String error;
private final String message;
private final String path;
private List<FieldError> fieldErrors; // Specifically for validation errors
// Constructor for general errors
public ErrorResponse(int status, String error, String message, String path) {
this.timestamp = Instant.now();
this.status = status;
this.error = error;
this.message = message;
this.path = path;
}
// Getters...
// Setter for fieldErrors
public void setFieldErrors(List<FieldError> fieldErrors) { this.fieldErrors = fieldErrors; }
// Inner static class for validation field errors
public static class FieldError {
private final String field;
private final String message;
public FieldError(String field, String message) {
this.field = field;
this.message = message;
}
// Getters...
}
}
Now, update GlobalExceptionHandler.java. We'll add a new method annotated with @ExceptionHandler(ResourceNotFoundException.class).
// In GlobalExceptionHandler.java
import com.example.blogplatform.exception.ResourceNotFoundException;
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.util.stream.Collectors;
import java.util.List;
@RestControllerAdvice
public class GlobalExceptionHandler {
// Our existing handler for VALIDATION exceptions
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationErrors(
MethodArgumentNotValidException ex, HttpServletRequest request) {
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.BAD_REQUEST.value(),
"Validation Failed",
"One or more fields have validation errors",
request.getRequestURI()
);
List<ErrorResponse.FieldError> fieldErrors = ex.getBindingResult().getFieldErrors().stream()
.map(error -> new ErrorResponse.FieldError(error.getField(), error.getDefaultMessage()))
.collect(Collectors.toList());
errorResponse.setFieldErrors(fieldErrors);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
// Our NEW handler for APPLICATION exceptions (specifically, ResourceNotFound)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFoundException(
ResourceNotFoundException ex, HttpServletRequest request) {
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
"Resource Not Found",
ex.getMessage(), // Get the message directly from our custom exception
request.getRequestURI()
);
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
}
Notice the clear separation: two distinct methods for two distinct exception types, each returning a different HTTP status and a tailored response body.
Runtime Observation: See the Difference
Time to see our work in action.
- Run the application in debug mode.
- Place a breakpoint inside the
handleResourceNotFoundExceptionmethod inGlobalExceptionHandler.java. - Using Postman, send a
GETrequest to an endpoint for a post that you know doesn't exist, e.g.,GET http://localhost:8080/api/posts/999. - Hit the breakpoint! Your IDE should pause. Inspect the
exvariable. You'll see it's an instance of ourResourceNotFoundException, and its message is "Post not found with id: 999". Look at the call stack to trace the execution flow from your service, where you threw the exception, all the way to this handler. - Resume execution. Check the Postman response. You will receive a
404 Not Foundstatus, and the JSON body will look like this:{ "timestamp": "...", "status": 404, "error": "Resource Not Found", "message": "Post not found with id: 999", "path": "/api/posts/999" } - Now, test the validation flow. Send a
POSTrequest to create a post with an invalid slug. You'll get a400 Bad Requestwith thefieldErrorslist, handled by the other method.
You have now successfully distinguished between and handled two different categories of exceptions.

Conclusion
Today, you've taken a massive step towards building a professional-grade API. By distinguishing between validation and application exceptions, you can provide clear, predictable, and context-aware feedback to your API clients. This separation of concerns is a hallmark of clean architecture.
Key Takeaways:
- Validation Exceptions (
MethodArgumentNotValidException) are for bad client input and result in a400 Bad Request. - Application Exceptions (like our
ResourceNotFoundException) are for business logic failures and map to various statuses like404 Not Foundor409 Conflict. You throw these manually. - The
@ControllerAdviceacts as a central point to handle all types of exceptions, with separate@ExceptionHandlermethods for each specific type. - Your service layer communicates business failures by throwing specific, unchecked exceptions. The web layer is responsible for translating these into appropriate HTTP responses.
Preview of the Next Lesson:
We now have a robust, well-structured API that can handle creating, reading, and persisting data with solid error handling. The next logical step is to secure it. In our next lesson, "Configure a Spring Security filter chain to secure endpoints," we will dive into Spring Security, the de-facto standard for authentication and authorization in the Java world. We'll compare its filter-based architecture to the middleware patterns you're familiar with from Express.js.