Unified Exception Handling in Spring: Using @ControllerAdvice, Assertions, and Enums for Clean Error Management
The article explains how to replace repetitive try‑catch blocks in Java Spring applications with a unified exception handling mechanism that leverages @ControllerAdvice, custom BaseException, Assert utilities, and enum‑based error codes to produce consistent, environment‑aware error responses.
During development, handling exceptions with repetitive try {...} catch {...} finally {...} blocks leads to noisy and hard‑to‑read code; the article proposes a cleaner approach using Spring's unified exception handling.
Unified Exception Handling is introduced via the @ControllerAdvice annotation, which allows a single class to intercept exceptions thrown from any @Controller or service layer.
The UnifiedExceptionHandler defines several @ExceptionHandler methods, for example:
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ErrorResponse handleBusinessException(BaseException e) {
log.error(e.getMessage(), e);
return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
}Custom exceptions extend BaseException, which carries an IResponseEnum containing an error code and message. By implementing BusinessExceptionAssert (which extends Assert), each enum constant can create the appropriate exception without writing separate classes.
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;
// getters omitted
}The Assert utility simplifies null checks:
public abstract class Assert {
public static void notNull(Object obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
}Various servlet‑related exceptions (e.g., NoHandlerFoundException, HttpRequestMethodNotSupportedException, MissingServletRequestParameterException) are captured in handleServletException, mapping each to a specific error code defined in enums such as CommonResponseEnum or ServletResponseEnum.
Environment awareness is added: when the active profile is prod, detailed internal messages are hidden and a generic SERVER_ERROR response is returned.
Finally, the article shows how to standardize API responses with BaseResponse, CommonResponse, ErrorResponse, and shortcut classes R and QR, ensuring every API returns a consistent code, message, and optional data payload.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
