Exception Handling: Dealing with the Unexpected Gracefully

6 min read

Welcome to the definitive guide on handling errors in Spring Boot. In the real world, software breaks. Databases go down, users send invalid data, and resources vanish. Your job as a developer is not to write code that never fails, but to write code that fails gracefully.

Let's explore how to manage the unexpected in a Spring Boot API, progressively moving from the basic concepts to modern industry standards.


1. The Reality of Errors: Why Good Handling Matters for APIs 🚨

Definition:
Exception handling is the programmatic process of anticipating, detecting, and resolving runtime errors in an application. It ensures that when something goes wrong, the program does not crash abruptly but instead responds with controlled, predictable behavior.

The Problem:
By default, when a Spring Boot application encounters an unhandled error, it generates a massive, complex block of text called a stack trace. If you do not handle the error, Spring Boot sends a generic 500 Internal Server Error and sometimes leaks this technical stack trace directly to the client (the frontend application or user).

Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly. If a customer orders a pizza that isn't on the menu (an error), and you, the chef, respond by dropping everything, throwing a flaming pan at the wall, and screaming a 50-page recipe manual in Italian (a raw stack trace), you are going to terrify the customer. They don't know what happened. You just need a system to calmly step in and say, "Sorry, that pizza is not on the menu today."

The Solution:
Good exception handling intercepts these crashes and translates them into meaningful HTTP status codes and clean JSON messages. Instead of crashing, your API politely informs the client exactly what went wrong (e.g., 404 Not Found or 400 Bad Request) so the client can take corrective action.


2. Global Exception Handling: @ControllerAdvice to the Rescue 🦸‍♂️

Definition:
@ControllerAdvice is a Spring annotation that allows you to consolidate your multiple, scattered @ExceptionHandler methods into a single, global error-handling component. It acts as an interceptor that catches exceptions thrown by any controller in your application.

The Problem:
When developers first learn to handle exceptions, they use standard try-catch blocks inside every single API endpoint.
If you have 50 endpoints, you end up writing 50 identical try-catch blocks. Your code becomes a bloated "spaghetti" of error-handling logic, making it impossible to read the actual business logic.

How @ControllerAdvice Solves It:
In industry, we almost never use try-catch in our REST controllers to handle API errors. Instead, we let the exception bubble up, and a centralized @ControllerAdvice class catches it globally.

Here is how you build a global exception handler:

java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    // This method catches ANY generic Exception thrown anywhere in the app
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception ex) {
        // We catch the error and return a clean 500 status with a simple message
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("An unexpected error occurred: " + ex.getMessage());
    }
}

How the flow works: When your PizzaController throws an error, Spring immediately stops executing the controller, searches for a class annotated with @ControllerAdvice, and routes the error to the matching @ExceptionHandler method.


3. Custom Exceptions: Meaningful Error States for Your Specific Domain 🏷️

Definition:
Custom exceptions are user-defined Java classes that extend the base RuntimeException (or Exception) class. They represent highly specific error states unique to your application's business logic.

The Problem:
Java provides built-in exceptions like IllegalArgumentException or NullPointerException. However, if your application throws an IllegalArgumentException, the global handler has no idea contextually what went wrong. Was the user ID invalid? Was the pizza crust type wrong? Relying on generic exceptions makes debugging a nightmare.

The Solution:
We create Domain-Specific Exceptions. In modern enterprise applications, you will often see exceptions mapped exactly to the business rules.

Let's create a custom exception for when a requested resource is not found:

java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

// We extend RuntimeException so we don't have to declare "throws" everywhere
public class ResourceNotFoundException extends RuntimeException {
    
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

Now, anywhere in your service layer, you can throw this specific exception:

java
public Pizza getPizzaById(Long id) {
    return pizzaRepository.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("Pizza with ID " + id + " was not found."));
}

Because it is a specific exception, we can add a dedicated handler for it in our @ControllerAdvice:

java
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
        // We know exactly what happened, so we return a 404 Not Found!
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(ex.getMessage());
    }
}

4. Formatting Standardized Error Responses: ProblemDetails API 📦

Definition:
The ProblemDetail API is Spring Boot 3's implementation of the RFC 7807 (and RFC 9457) specification. It is a globally recognized standard for structuring JSON error responses in HTTP APIs.

The Problem:
Historically, every company—and sometimes every team within a company—invented their own JSON structure for errors.

Team A would return: {"error": "Not Found"}
Team B would return: {"message": "Not Found", "code": 404}
Team C would return: {"errorMessage": "Not Found", "timestamp": "10:00"}

Interesting Fact: Before RFC 7807 became the industry standard, software companies wasted millions of collective developer hours just arguing in meeting rooms about whether the error JSON field should be named errorMessage, message, error_description, or details.

Frontend developers had to write complex code to guess which format the backend was sending.

The Solution:
Spring Boot 3 solves this by supporting ProblemDetail out of the box. It enforces a strict, standard JSON shape that includes specific fields: type, title, status, detail, and instance.

Step 1: Enable it in your configuration

To get started with the latest Spring Boot standard, you don't even need to write extra code for default Spring errors. Just add one line to your application.properties (or .yml):

properties
# application.properties
spring.mvc.problemdetails.enabled=true

Step 2: Use ProblemDetail in your Custom Exceptions

Now, let's update our GlobalExceptionHandler to return this beautiful, standardized ProblemDetail object instead of a plain String.

java
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.net.URI;
import java.time.Instant;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ProblemDetail handleResourceNotFoundException(ResourceNotFoundException ex) {
        
        // 1. Create the ProblemDetail object with status and detail message
        ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        
        // 2. Set a human-readable title
        problemDetail.setTitle("Resource Not Found");
        
        // 3. (Optional) Set a URI that points to documentation about this error
        problemDetail.setType(URI.create("https://api.yourpizzashop.com/errors/not-found"));
        
        // 4. (Optional) Add custom properties specific to your business needs
        problemDetail.setProperty("timestamp", Instant.now());
        
        return problemDetail;
    }
}

The Resulting Output

When a user requests a missing pizza now, they don't get a screaming stack trace. They don't get a random, unpredictable JSON shape. They get a pristine, industry-standard response:

json
{
  "type": "https://api.yourpizzashop.com/errors/not-found",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "Pizza with ID 99 was not found.",
  "instance": "/api/pizzas/99",
  "timestamp": "2026-02-25T05:22:00.000Z"
}

Frontend frameworks and automated clients understand this format universally. You have successfully tamed the chaos of backend errors!


Further Reading & References 📚

If you want to dive deeper into the technical specifications and underlying mechanisms of what we covered today, check out these official resources:

Challenge

Challenge: Implement a Global Exception Handler with ProblemDetail

Your task is to implement a robust, centralized exception handling mechanism for a Spring Boot application using @ControllerAdvice and the standard ProblemDetail API.

Requirements:

  1. Create a Custom Exception: Define a public class named ProductNotFoundException that extends RuntimeException. It must have a single public constructor that accepts a String message.

  2. Create a Global Handler: Define a public class named GlobalExceptionHandler. Annotate this class so that it can provide centralized exception handling across all controllers.

  3. Implement a Specific Handler: Inside GlobalExceptionHandler, create a public method that specifically handles ProductNotFoundException. This method must:

    • Be annotated to act as an exception handler for ProductNotFoundException.
    • Return a ProblemDetail object.
    • The ProblemDetail must be configured for an HTTP 404 NOT_FOUND status.
    • The detail field of the ProblemDetail must be populated with the message from the caught ProductNotFoundException.
  4. Implement a Generic Fallback Handler: Inside GlobalExceptionHandler, create a second public method to act as a fallback for any other uncaught Exception. This method must:

    • Be annotated to handle the generic Exception class.
    • Return a ProblemDetail object.
    • The ProblemDetail must be configured for an HTTP 500 INTERNAL_SERVER_ERROR status.
    • The detail field of the ProblemDetail must be set to the static string: "An unexpected internal server error occurred."

Expected result

Your solution should consist of two complete Java classes. The first is the custom exception, and the second is the annotated global handler containing two distinct handler methods.

ProductNotFoundException.java

The custom exception class must extend RuntimeException and provide a constructor that calls its parent with the error message.

java
public class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}

GlobalExceptionHandler.java

This class must be annotated with @ControllerAdvice and contain two methods, each annotated with @ExceptionHandler for their respective exception types. Both methods should correctly construct and return a ProblemDetail object corresponding to the requirements.

java
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ProductNotFoundException.class)
    public ProblemDetail handleProductNotFoundException(ProductNotFoundException ex) {
        ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problemDetail.setTitle("Product Not Found");
        return problemDetail;
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail handleGenericException(Exception ex) {
        ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected internal server error occurred.");
        problemDetail.setTitle("Internal Server Error");
        return problemDetail;
    }
}
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.