About Us Contact Us Write for Us Advertise
Home > Java > Spring Boot Exception Handling Done Right (Beginner Guide)
Java

Spring Boot Exception Handling Done Right (Beginner Guide)

Handle errors professionally in Spring Boot: global exception handling with @RestControllerAdvice, custom exceptions, correct status codes, and clean consistent error responses.

Shiv Pandey
Shiv Pandey
Oct 05, 2026 | 117 views
Spring Boot Exception Handling Done Right (Beginner Guide)

Things go wrong: a user requests a record that doesn't exist, a database hiccups, something unexpected throws an exception. How your API responds to errors is a hallmark of professional code. In this lesson you'll learn Spring Boot's elegant way to handle exceptions globally — turning ugly stack traces into clean, consistent error responses your clients can actually work with.

The problem with unhandled exceptions

By default, when your code throws an exception that isn't caught, Spring Boot returns a generic 500 Internal Server Error — often with a messy stack trace. That's bad for two reasons: it leaks internal details (a security concern), and it gives the client no useful information. A "user not found" situation shouldn't look like a server crash; it should be a clean 404 with a clear message.

The naive approach (and why it doesn't scale)

You could wrap every controller method in try-catch blocks. But that means repeating the same error-handling code everywhere — cluttered, inconsistent, and easy to get wrong. Spring offers something far better: handle exceptions in one central place.

The solution: @RestControllerAdvice

A class annotated with @RestControllerAdvice acts as a global exception handler. Any exception thrown anywhere in your controllers gets routed here, where you decide how to respond. Write it once, and every endpoint benefits:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)      // 404
    public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
        return new ErrorResponse("NOT_FOUND", ex.getMessage());
    }

    @ExceptionHandler(Exception.class)          // catch-all fallback
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  // 500
    public ErrorResponse handleGeneral(Exception ex) {
        return new ErrorResponse("SERVER_ERROR", "Something went wrong");
    }
}
  • @ExceptionHandler(SomeException.class) — "when this exception is thrown, run this method."
  • @ResponseStatus(...) — set the correct HTTP status code for that error.
  • The returned object becomes the clean JSON error body the client receives.

Creating your own exceptions

Custom exceptions make your code readable and your error handling precise. Define a simple one for "not found":

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

Now your service can simply throw it, trusting the global handler to turn it into a proper 404:

public User findById(Long id) {
    return repo.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("User " + id + " not found"));
}

Look how clean this is: the service just says "throw not-found if it's missing," and the response formatting happens centrally. Your business logic stays focused, and error handling lives in one predictable place.

A consistent error response shape

Good APIs return errors in a consistent structure, so clients can reliably parse them. A simple ErrorResponse class does the job:

// what the client receives, every time:
{
  "code": "NOT_FOUND",
  "message": "User 42 not found"
}
Security tip: in your catch-all handler, return a generic message ("Something went wrong") rather than the raw exception details. Log the full exception on the server for your own debugging, but never expose internal stack traces or database errors to clients — attackers can use that information. Helpful to you, opaque to them.

Global exception handling was a genuine "level up" moment in my Spring Boot journey — the point where my APIs started feeling professional rather than like student projects. Before it, my error responses were a chaotic mix of stack traces and inconsistent messages; after, every error came back clean and predictable, and my controllers got dramatically simpler because all that try-catch clutter vanished. My advice: set up a @RestControllerAdvice early in any project, define a couple of custom exceptions, and let your services throw freely. This website routes every error through exactly this kind of central handler — it's one of the highest-value patterns you'll learn here.

Key takeaways

  • Unhandled exceptions return ugly, leaky 500s — handle errors deliberately instead.
  • @RestControllerAdvice + @ExceptionHandler handle exceptions globally, in one place.
  • Define custom exceptions (e.g. ResourceNotFoundException) and throw them; map each to the right status code.
  • Return a consistent error shape, and keep internal details out of client-facing messages (log them instead).

← Previous: Spring Lesson 7 — Validation
Next: Spring Lesson 9 — Configuration & Profiles →
↑ Back to the Spring Boot roadmap

Related Articles

Spring vs Spring Boot: The Difference Explained (Beginner Guide)
Java

Spring vs Spring Boot: The Difference Explained (Beginner Guide)

Spring Boot Project Ideas (Beginner to Advanced)
Java

Spring Boot Project Ideas (Beginner to Advanced)

Deploying a Spring Boot App to Production (Beginner Guide)
Java

Deploying a Spring Boot App to Production (Beginner Guide)

Dockerizing a Spring Boot App (Beginner Guide)
Java

Dockerizing a Spring Boot App (Beginner Guide)