Backend Development 22 min read

Unified Exception Handling in Spring Boot Using @ControllerAdvice, Assertions, and Enums

This article explains how to replace repetitive try‑catch blocks in Spring Boot applications with a unified exception handling mechanism that leverages @ControllerAdvice, custom Assert utilities, and enum‑based error codes to produce clean, maintainable backend code.

Top Architect
Top Architect
Top Architect
Unified Exception Handling in Spring Boot Using @ControllerAdvice, Assertions, and Enums

Background – In Java projects a large amount of code is occupied by repetitive try { ... } catch { ... } finally { ... } blocks, which reduces readability and increases maintenance cost.

What is Unified Exception Handling – Spring 3.2 introduced @ControllerAdvice that can be combined with @ExceptionHandler to centralize exception processing for all controllers, eliminating the need to duplicate handling logic.

Using Assertions – Instead of manual if (obj == null) { throw new IllegalArgumentException(...); } checks, Spring's org.springframework.util.Assert provides concise validation methods such as Assert.notNull(obj, "User not found.") . The article shows how to create a custom Assert interface that returns domain‑specific exceptions.

Enum‑Based Exception Definition – By defining an enum that implements a BusinessExceptionAssert interface, each error scenario (e.g., BAD_LICENCE_TYPE , LICENCE_NOT_FOUND ) carries a unique error code and message, allowing the assertion to throw a BusinessException with the appropriate enum value.

public interface Assert {
    static void notNull(Object object, String message) {
        if (object == null) {
            throw new IllegalArgumentException(message);
        }
    }
}

The service layer can then use the enum assertions directly:

private void checkNotNull(Licence licence) {
    ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
}

Unified Exception Handler – A class annotated with @ControllerAdvice defines multiple @ExceptionHandler methods to catch business exceptions, framework exceptions, validation errors, and any unknown exceptions, converting them into a standard ErrorResponse containing code and message . The handler also respects the active Spring profile to hide technical details in production.

@Slf4j
@Component
@ControllerAdvice
public class UnifiedExceptionHandler {
    private static final String ENV_PROD = "prod";
    @Autowired
    private UnifiedMessageSource unifiedMessageSource;
    @Value("${spring.profiles.active}")
    private String profile;
    // ... handler methods omitted for brevity ...
}

Unified Response Structure – All API responses inherit from BaseResponse and include code , message , and optionally data . Helper classes R and QR provide concise ways to return success results.

Testing the Mechanism – The article demonstrates how various error scenarios (missing entity, invalid licence type, 404 not found, method not allowed, validation failures, and database errors) are captured by the unified handler and returned with consistent error codes and localized messages.

Conclusion – Combining assertions, enum‑based error definitions, and a global @ControllerAdvice handler dramatically reduces boilerplate try‑catch code, improves readability, and provides a uniform error‑response contract for backend services.

backendJavaException HandlingSpringSpringBootenumsAssertions
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.