Unified Exception Handling in Spring Using @ControllerAdvice, Assertions, and Enums
This article explains how to replace repetitive try‑catch blocks in Java Spring applications with a clean, unified exception handling approach that leverages @ControllerAdvice, custom Assert utilities, enum‑based error codes, and standardized response objects to improve code readability and maintainability.
In Java Spring development, handling numerous try‑catch blocks leads to redundant and hard‑to‑read code. The article first contrasts a messy try‑catch style with a cleaner controller approach, then introduces Spring 3.2's @ControllerAdvice annotation for centralized exception handling.
It describes how to define a unified exception handling class annotated with @ControllerAdvice, @Component, and conditional annotations, which captures various exception types—including servlet‑level errors, binding errors, custom business exceptions, and unknown exceptions—returning a consistent ErrorResponse containing a code and message.
The article also shows how to use Spring's org.springframework.util.Assert for concise validation, providing code examples of Assert usage in tests and service methods, and demonstrates creating a custom Assert interface that throws domain‑specific exceptions based on enum definitions.
Enums are used to encapsulate error codes and messages (e.g., BAD_LICENCE_TYPE , LICENCE_NOT_FOUND ), allowing new error scenarios to be added simply by defining new enum instances rather than new exception classes.
It further details how to map different exception stages (pre‑controller, service layer) to specific handler methods ( handleServletException , handleBindException , handleValidException , handleBusinessException , handleBaseException , handleException ), and explains environment‑aware error messages that hide technical details in production.
Additional topics include configuring Spring to throw exceptions for 404 errors, using unified response wrappers ( BaseResponse , CommonResponse , QueryDataResponse ), and providing sample service code that demonstrates validation with the custom Assert and enum‑based error handling.
Finally, the article offers a summary, notes on extending the approach for security and remote‑call errors, and mentions internationalization of error messages via a message source.
IT Architects Alliance
Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.
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.