Global Exception Handling in Spring Boot with @ControllerAdvice

When building RESTful APIs with Spring Boot, exception handling becomes critical for providing meaningful responses and avoiding verbose stack traces in the client response. Rather than handling exceptions in every controller, Spring Boot offers a clean, centralized way: @ControllerAdvice.

In this guide, we’ll explore:

  • What is @ControllerAdvice
  • Handling exceptions globally
  • Returning structured JSON responses
  • Customizing error messages
  • Real-world patterns
Global Exception Handling in Spring Boot

🔍 What is @ControllerAdvice?

@ControllerAdvice is a specialization of @Component used to define global exception handling logic across the entire application. You can catch, log, and respond to exceptions thrown in your controllers—all in one place.

✅ Setup Spring Boot Project

Ensure your project has the following dependency:

Spring Boot’s web starter already configures Jackson and basic exception handling infrastructure.

💥 Example: Throwing an Exception

Let’s create a simple REST controller that might throw an exception:

📂 Controller: UserController.java

This controller throws IllegalArgumentException for invalid IDs.

🧰 Global Exception Handling with @ControllerAdvice

Create a global handler class:

📁 GlobalExceptionHandler.java

🔁 Sample Error Response

🧪 Testing the Endpoint

Returns HTTP 400 Bad Request with the structured JSON error.

🧩 Validating Input with @Valid + Exception Handling

Let’s add a POST endpoint and handle validation errors.

📁 User.java

📁 UserController.java

➕ Add Handler for Validation Errors

🔁 Sample Response

🧼 Clean Error Model (Optional)

Create a custom error response model:

Modify Handler

🧾 Best Practices

TipDescription
Use specific exception classese.g., UserNotFoundException, InvalidRequestException
Return standard structureHelps front-end developers consume error responses consistently
Avoid exposing internalsNever return full stack trace or DB error directly
Log the errorsUse SLF4J/Logback to log details for debugging
Use @ResponseStatus for simple use casesOn custom exceptions if JSON body is not needed

📚 External References

✅ Conclusion

Using @ControllerAdvice, you can manage exceptions in a centralized and consistent way, improving API design and maintainability. With structured responses and specific handlers, your applications become more robust and developer-friendly.