Unified Exception Handling in Spring Boot Using @ControllerAdvice, Custom Assertions, and Enums
This article explains how to replace repetitive try‑catch blocks in Java Spring applications with a unified exception handling mechanism that leverages @ControllerAdvice, custom Assert utilities, enum‑based error codes, and standardized response objects to improve code readability, maintainability, and internationalization.
In Java Spring development, excessive try‑catch blocks make code redundant and hard to read. The article proposes using try {...} catch {...} finally {...} sparingly and instead handling exceptions centrally.
Spring 3.2 introduced @ControllerAdvice and @ExceptionHandler , which can be applied to all controllers to define global exception handlers without coupling each controller to specific error‑handling code.
A custom Assert interface is created to replace manual null checks with Assert.notNull() , throwing business‑specific exceptions defined by enums that contain an error code and message.
Enums implementing BusinessExceptionAssert map each error scenario (e.g., BAD_LICENCE_TYPE , LICENCE_NOT_FOUND ) to a concrete BusinessException , eliminating the need for many separate exception classes.
The unified exception handler class annotated with @ControllerAdvice defines methods such as handleBusinessException , handleBaseException , handleServletException , handleBindException , and a generic handleException to process custom, servlet, validation, and unknown exceptions respectively, returning a consistent ErrorResponse containing code and message .
Special handling for production environments hides detailed error messages, returning generic messages like "Network error". Internationalization is supported by mapping error codes to localized messages.
Standard response structures ( BaseResponse , CommonResponse , QueryDataResponse ) and shortcut classes ( R , QR ) are introduced to unify API outputs.
Extensive code snippets illustrate the implementation of the Assert utilities, enums, exception handler, and service layer usage, demonstrating how to validate inputs, query data, and handle errors consistently across the application.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.