Backend Development 22 min read

Unified Exception Handling in Spring Boot: Design, Implementation, and Best Practices

This article explains how to design and implement a unified exception handling framework in Spring Boot applications, covering background, the use of @ControllerAdvice and @ExceptionHandler, custom assertion utilities, error response structures, handling of various exception types, and practical validation examples with code snippets.

Top Architect
Top Architect
Top Architect
Unified Exception Handling in Spring Boot: Design, Implementation, and Best Practices

In large‑scale Java services, scattered try { ... } catch { ... } blocks make code noisy and hard to read; a unified approach to exception handling improves maintainability and readability.

Spring 3.2 introduced @ControllerAdvice and @ExceptionHandler , allowing developers to define global exception handlers that apply to all controllers without inheritance.

A custom Assert interface replaces repetitive if (obj == null) { throw new IllegalArgumentException(...); } checks with expressive assertions such as Assert.notNull(obj, "msg") . Example:

public interface Assert {
    default void assertNotNull(Object obj) {
        if (obj == null) {
            throw new IllegalArgumentException("Object must not be null");
        }
    }
}

Business error codes and messages are encapsulated in an enum that implements BusinessExceptionAssert . Each enum constant holds a code and a message , and creates a specific BusinessException when the assertion fails.

public enum ResponseEnum implements BusinessExceptionAssert {
    BAD_LICENCE_TYPE(7001, "Bad licence type."),
    LICENCE_NOT_FOUND(7002, "Licence not found.");
    private final int code;
    private final String message;
    // methods to create exceptions
}

The core UnifiedExceptionHandler class, annotated with @ControllerAdvice , defines several @ExceptionHandler methods:

handleBusinessException – processes custom BusinessException and returns an ErrorResponse with the enum’s code and localized message.

handleBaseException – catches other BaseException types.

handleServletException – deals with framework‑level exceptions such as NoHandlerFoundException , HttpRequestMethodNotSupportedException , etc.

handleBindException / handleValidException – aggregates validation errors into a single readable message.

handleException – a fallback for any uncaught exceptions, optionally masking details in production.

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

To make 404 errors throw exceptions instead of rendering the default Whitelabel page, the properties spring.mvc.throw-exception-if-no-handler-found=true and spring.resources.add-mappings=false are set, allowing the handler above to capture NoHandlerFoundException .

All API responses share a unified structure containing code , message , and optional data . Helper classes R<T> and QR<T> simplify returning normal and paginated results.

In production environments the handler replaces detailed internal messages with a generic "Network error" to avoid exposing stack traces to end users.

Overall, the article demonstrates how combining @ControllerAdvice , assertion utilities, enum‑based error codes, and a consistent response model yields a clean, maintainable, and internationalized exception handling solution for backend Java applications.

backendSpringExceptionHandlingUnifiedError
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.