Unified Exception Handling in Spring Boot: Best Practices and Implementation
This article explains how to replace repetitive try‑catch blocks with a unified exception handling approach in Spring Boot using @ControllerAdvice, @ExceptionHandler, custom Assert utilities, and enumerated error codes, providing clean code, consistent error responses, and easy internationalization.
In Java backend development, handling exceptions with repetitive try { ... } catch { ... } finally { ... } blocks leads to noisy and hard‑to‑read code. The article first shows the contrast between a cluttered try‑catch style and a clean controller implementation.
Spring 3.2 introduced @ControllerAdvice and @ExceptionHandler annotations, which allow developers to define global exception handlers that apply to all controllers, eliminating the need for duplicated error handling code in each controller or service.
To further simplify validation, the article proposes using an Assert utility (similar to org.springframework.util.Assert ) that throws custom exceptions when conditions fail. Example:
public abstract class Assert {
public static void notNull(Object obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
}Custom business exceptions are built on a BaseException that carries an IResponseEnum containing an error code and message . An enum such as:
public enum ResponseEnum implements BusinessExceptionAssert {
BAD_LICENCE_TYPE(7001, "Bad licence type."),
LICENCE_NOT_FOUND(7002, "Licence not found.");
private int code;
private String message;
}can be used to assert conditions, e.g., ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence); , automatically throwing a BusinessException with the appropriate code and message.
The core of the solution is a UnifiedExceptionHandler annotated with @ControllerAdvice . It defines handlers for:
Business exceptions ( @ExceptionHandler(BusinessException.class) )
Base exceptions ( @ExceptionHandler(BaseException.class) )
Servlet‑related exceptions (404, method not supported, missing parameters, etc.)
Binding and validation errors ( BindException , MethodArgumentNotValidException )
All other uncaught exceptions
Each handler logs the error and returns a unified JSON response containing code , message , and optionally data . In production mode, generic messages are returned to avoid exposing internal details.
The article also shows how to configure Spring to throw a NoHandlerFoundException for unmapped URLs, enabling 404 handling via the same unified mechanism.
Finally, a series of test cases demonstrate the handling of custom business errors, validation failures, HTTP method mismatches, and unexpected database errors, confirming that the unified approach consistently returns structured error information.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.