Backend Development 21 min read

Unified Exception Handling in Spring Boot Using @ControllerAdvice, Assert, and Enum‑Based Business Errors

This article explains how to replace repetitive try‑catch blocks in Java Spring applications with a unified exception handling strategy that leverages @ControllerAdvice, custom Assert utilities, enum‑based error codes, and standardized response objects to improve code readability, maintainability, and internationalisation.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Unified Exception Handling in Spring Boot Using @ControllerAdvice, Assert, and Enum‑Based Business Errors

During Java development, developers often write many try { ... } catch { ... } finally { ... } blocks, which makes the code verbose and hard to read. The article first shows an "ugly" try‑catch style and a cleaner controller style, then introduces Spring 3.2's @ControllerAdvice and @ExceptionHandler annotations for centralized exception handling.

Using @ControllerAdvice , a single class can define methods that handle all exceptions thrown from any controller, eliminating the need to duplicate error‑handling code in each controller or to create a base controller class.

To further simplify validation, the article recommends replacing explicit if (obj == null) { throw new IllegalArgumentException(...); } checks with Spring's org.springframework.util.Assert style assertions. A custom Assert interface is shown:

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

For business‑specific errors, the article proposes an enum that implements a BusinessExceptionAssert interface, providing both an error code and a message. Example:

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;
}

The enum supplies newException methods that create a BusinessException carrying the enum's code and formatted message, allowing callers to write concise validation such as:

ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum);

A complete UnifiedExceptionHandler class is presented, annotated with @ControllerAdvice and containing methods like handleBusinessException , handleBaseException , handleServletException , handleBindException , handleValidException , and a generic handleException . Each method logs the error, determines an appropriate error code (using enums such as CommonResponseEnum or ServletResponseEnum ), and returns a standardized ErrorResponse object.

The article also explains how to make 404 errors throw exceptions by setting spring.mvc.throw-exception-if-no-handler-found=true and disabling static resource mappings, enabling the unified handler to capture missing‑endpoint errors.

Finally, a unified response model is described: a base class containing code and message , a CommonResponse that adds a data field, and shortcut classes R and QR for simple success responses. The article demonstrates testing the handler with various scenarios (missing resources, invalid parameters, database errors) and shows screenshots of the resulting JSON payloads.

backendJavaSpringenumMyBatisAssertExceptionHandling
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

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.