Elegant Exception Handling in Spring: Replace try‑catch with Assert and @ControllerAdvice
The article demonstrates how to eliminate repetitive try‑catch blocks in Java Spring applications by using Spring's @ControllerAdvice for centralized exception handling, a custom Assert interface backed by enums for error codes, and unified response objects, resulting in cleaner, more maintainable code.
In typical Java services a large portion of the code consists of repetitive try { … } catch (Exception e) { … } blocks, which makes the source noisy and hard to read.
Spring MVC offers @ControllerAdvice together with @ExceptionHandler to move all exception processing to a single class, so controllers can focus on business logic.
Instead of writing explicit if (obj == null) throw new IllegalArgumentException(...) the author suggests using Spring's org.springframework.util.Assert style checks. A custom Assert interface is defined, whose default methods delegate to an enum that holds an error code and a message template.
public interface Assert {
default void assertNotNull(Object obj) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
// other assert methods …
}
public enum ResponseEnum implements Assert {
BAD_LICENCE_TYPE(7001, "Bad licence type."),
LICENCE_NOT_FOUND(7002, "Licence not found.");
private final int code;
private final String message;
// getters and constructor …
}Service code can then write concise checks such as:
ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum);
ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);The unified exception handler UnifiedExceptionHandler captures various exception categories: @ExceptionHandler(BusinessException.class) – custom business errors. @ExceptionHandler(BaseException.class) – other domain errors.
@ExceptionHandler({NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class, …})– servlet‑level problems such as 404, method not allowed, missing parameters, etc. @ExceptionHandler(BindException.class) and @ExceptionHandler(MethodArgumentNotValidException.class) – validation failures. @ExceptionHandler(Exception.class) – any unexpected exception.
Each handler builds an ErrorResponse containing a code and a localized message. The helper method getMessage(BaseException e) looks up the message from a MessageSource using the enum name, allowing easy i18n.
@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 Spring throw a NoHandlerFoundException for unmapped URLs (instead of the default Whitelabel error page), the following properties are added:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=falseFor a consistent API contract the article defines a hierarchy of response objects: BaseResponse (contains code and message), CommonResponse (adds data), ErrorResponse (error only), and shortcut wrappers R<T> and QR<T> for success and paginated results.
Testing shows that custom enum‑based asserts raise the correct error codes, 404 and method‑not‑allowed requests are captured by handleServletException, validation errors are aggregated into a readable message, and unknown runtime errors are reported as a generic server‑error code. In production mode the handler can replace detailed stack traces with a generic "Network error" message.
Overall, the article provides a step‑by‑step guide: replace verbose try‑catch with enum‑driven asserts, centralize all exception handling with @ControllerAdvice, and return a uniform response structure, greatly improving code readability and maintainability.
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.
