Unified Exception Handling in Spring Boot: Design, Implementation, and Practical Examples
This article explains how to design and implement a unified exception handling framework in Spring Boot, covering background, annotation usage, custom assertions, enum-based error codes, detailed handler methods, response structures, and practical validation examples with code snippets.
In modern Java backend development, handling exceptions consistently across the service and controller layers is essential for code readability and maintainability. This article introduces a unified exception handling solution for Spring Boot applications, starting with the problem of scattered try { ... } catch { ... } blocks and the need for a cleaner approach.
What is Unified Exception Handling? Spring 3.2 introduced @ControllerAdvice and @ExceptionHandler to apply exception handlers globally. By combining these annotations with custom assertion utilities, developers can centralize error processing without coupling to specific controllers.
Custom Assertion Interface
public abstract class Assert {
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
}To make assertions return domain‑specific exceptions, an Assert interface is extended with default methods that create BaseException instances based on an IResponseEnum:
public interface BusinessExceptionAssert extends IResponseEnum, Assert {
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
}An enum implements this interface, defining error codes and messages:
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
}UnifiedExceptionHandler is a @ControllerAdvice component that defines several @ExceptionHandler methods to process different exception categories:
@ExceptionHandler(BusinessException.class)
@ResponseBody
public ErrorResponse handleBusinessException(BaseException e) {
log.error(e.getMessage(), e);
return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
}
@ExceptionHandler({ NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class, ... })
@ResponseBody
public ErrorResponse handleServletException(Exception e) {
log.error(e.getMessage(), e);
int code = CommonResponseEnum.SERVER_ERROR.getCode();
// map specific servlet exceptions to enum codes
return new ErrorResponse(code, getMessage(e));
}The handler also distinguishes production environments, returning generic messages for security‑sensitive errors.
Standard Response Structure – All API responses inherit from BaseResponse containing code and message. Successful results use CommonResponse (with optional data) or QueryDataResponse for paginated data. Helper classes R<T> and QR<T> provide concise constructors.
Practical Validation – The article demonstrates how to use the enum‑based assertions in service methods, e.g.:
private void checkNotNull(Licence licence) {
ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
}
public QueryData<SimpleLicenceDTO> getLicences(LicenceParam param) {
LicenceTypeEnum type = LicenceTypeEnum.parseOfNullable(param.getLicenceType());
ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(type);
// query logic omitted
}Various test scenarios are shown: missing resources (404), unsupported HTTP methods, parameter binding errors, and unexpected database errors. Each case is captured by the appropriate handler, returning a consistent {"code":..., "message":...} JSON payload.
Conclusion – By combining @ControllerAdvice, custom assertion interfaces, and enum‑driven error codes, developers can achieve a clean, maintainable, and internationally‑ready exception handling strategy for Spring Boot back‑ends.
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.
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.
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.
