Mastering Unified Exception Handling in Spring: Clean Code with Assert and Enums

This article explains how to replace repetitive try‑catch blocks in Java Spring applications with a unified @ControllerAdvice error handler, lightweight Assert utilities, and enum‑based error codes, resulting in cleaner code, consistent JSON responses, and easier maintenance across backend services.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Unified Exception Handling in Spring: Clean Code with Assert and Enums

Why Clean Up Try‑Catch Blocks?

In Java projects a large portion of code is occupied by repetitive try‑catch‑finally blocks, which makes the source hard to read and maintain.

Two coding styles are shown: a “ugly” controller filled with try‑catch statements and a cleaner version that delegates error handling.

Unified Exception Handling with @ControllerAdvice

Spring 3.2 introduced @ControllerAdvice, which can be combined with @ExceptionHandler to apply a single exception‑handling method to all controllers, avoiding duplicated code.

The handler can capture business exceptions, servlet‑level errors, validation failures and unknown exceptions, returning a consistent JSON structure.

Using Assert for Business Validation

Spring’s org.springframework.util.Assert simplifies null checks and other validations. Example test methods demonstrate replacing verbose if‑null checks with Assert.notNull.

@Test
public void test1() {
    User user = userDao.selectById(userId);
    Assert.notNull(user, "User does not exist.");
}

Custom Assert Interface with Enum‑Based Error Codes

A custom Assert interface defines default methods that create BaseException instances. An IResponseEnum supplies an error code and message, allowing each business rule to be represented by an enum constant.

public interface Assert {
    BaseException newException(Object... args);
    default void assertNotNull(Object obj) {
        if (obj == null) {
            throw newException(obj);
        }
    }
}

Defining Business Exceptions and Enums

The BusinessException class extends BaseException. An enum ResponseEnum implements BusinessExceptionAssert and lists concrete error scenarios such as BAD_LICENCE_TYPE (code 7001) and LICENCE_NOT_FOUND (code 7002).

public enum ResponseEnum implements BusinessExceptionAssert {
    BAD_LICENCE_TYPE(7001, "Bad licence type."),
    LICENCE_NOT_FOUND(7002, "Licence not found.");
}

Unified Exception Handler Implementation

The UnifiedExceptionHandler class is annotated with @ControllerAdvice and defines methods for handling BusinessException, generic BaseException, servlet‑related exceptions, binding errors, and any other Exception. It logs the error and returns an ErrorResponse containing the code and localized message.

@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ErrorResponse handleBusinessException(BaseException e) {
    log.error(e.getMessage(), e);
    return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
}

Testing the Handler

Various HTTP requests (missing resources, unsupported methods, validation errors, unknown database errors) are sent to demonstrate that the handler captures each case and returns a JSON payload with code and message. Screenshots illustrate the responses.

Whitelabel Error Page
Whitelabel Error Page

Production‑Environment Considerations

When the active profile is “prod”, the handler hides technical details and returns a generic “Network error” message to avoid exposing internal stack traces.

Conclusion

Combining @ControllerAdvice, a lightweight Assert utility, and enum‑based error definitions yields a maintainable, readable codebase with consistent error responses across all layers of a Spring backend application.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaException HandlingspringenumAssertUnifiedError
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

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.