Backend Development 20 min read

Unified Exception Handling in Spring Boot Using Assert and Enum-based Error Codes

This article demonstrates how to replace repetitive try‑catch blocks in Java Spring applications with a unified exception handling approach that leverages @ControllerAdvice, custom Assert utilities, and enum‑based error codes to produce clean, maintainable, and internationalized error responses across controllers and services.

Java Captain
Java Captain
Java Captain
Unified Exception Handling in Spring Boot Using Assert and Enum-based Error Codes

In Java backend development, handling exceptions often leads to scattered try { ... } catch { ... } finally { ... } blocks that clutter code and reduce readability. The article first shows the contrast between a messy try‑catch style and a cleaner controller implementation.

Spring 3.2 introduced @ControllerAdvice , which can be combined with @ExceptionHandler to define global exception handling logic that applies to all controllers, eliminating the need for repetitive error handling code in each controller class.

The author proposes using a custom Assert interface with default methods such as assertNotNull that internally throw a BaseException . By defining business-specific enums (e.g., ResponseEnum ) that implement BusinessExceptionAssert , each error scenario can be represented by a code and message without creating a separate exception class for every case.

Key code snippets include:

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

and the enum‑based error definition:

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;
    // getters omitted
}

A UnifiedExceptionHandler class annotated with @ControllerAdvice handles various exception categories:

Business exceptions ( BusinessException ) and generic base exceptions, returning an ErrorResponse with the enum's code and a localized message.

Servlet‑related exceptions (e.g., NoHandlerFoundException , HttpRequestMethodNotSupportedException ) with environment‑aware messages, defaulting to a generic server error in production.

Binding and validation errors ( BindException , MethodArgumentNotValidException ) that aggregate field errors into a single message.

All other uncaught exceptions, also returning a generic error response in production.

The handler also demonstrates how to configure Spring to throw an exception for 404 errors by setting spring.mvc.throw-exception-if-no-handler-found=true and disabling static resource mappings.

Unified response structures are defined with a base class containing code and message , and subclasses such as CommonResponse and QueryDataResponse that add a data field. For convenience, short aliases R and QR are introduced.

The article concludes with a practical verification using a sample LicenceService that shows how the unified handling captures custom business errors, validation failures, missing endpoints, unsupported HTTP methods, and even database schema mismatches, providing consistent error codes and messages to the client.

backendJavaException HandlingSpringenumAssertUnified API
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

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.