SpringBoot Global Exception Handling: Build a Clean, Unified Error Strategy
This guide walks through building a complete global exception handling system in SpringBoot using @ControllerAdvice and @ExceptionHandler, covering unified response structures, custom business exceptions, validation error handling, logging best practices, and security considerations to keep controllers clean and maintainable.
Why Global Exception Handling Matters
In traditional SpringBoot development, controllers often become cluttered with repetitive try-catch blocks for every endpoint. The example shows a typical createUser method wrapped in multiple catch clauses handling BizException and generic Exception, each returning a Result object with error codes and messages. This approach bloats business logic and makes format changes costly across dozens of endpoints. SpringBoot's global exception handling mechanism decouples error handling from business code entirely.
Core Annotations: @ControllerAdvice + @ExceptionHandler
Two annotations form the foundation:
@ControllerAdvice : Defines a global enhancer for controllers, typically paired with @ExceptionHandler.
@ExceptionHandler : Maps a specific exception type to a handler method.
Building the Unified Exception System
1. Unified Response Body (Result)
A generic Result<T> class standardizes all API responses with three fields: code (Integer), message (String), and data (T). Static factory methods success(T), success(), and fail(Integer, String) simplify construction. The class uses Lombok annotations @Data, @AllArgsConstructor, @NoArgsConstructor.
2. Business Exception Hierarchy
BizExceptionextends RuntimeException and carries a final code field. Two constructors accept either (Integer code, String message) or an ErrorCode enum. The ErrorCode enum centralizes error definitions (e.g., USER_NOT_FOUND(1001, "用户不存在"), USER_ALREADY_EXISTS(1002, "用户已存在"), PARAM_ERROR(1003, "参数错误")), each with code and message fields.
3. Global Exception Handler (GlobalExceptionHandler)
The class is annotated with @Slf4j and @RestControllerAdvice. Four handler methods demonstrate layered exception handling:
Business exceptions : @ExceptionHandler(BizException.class) logs at warn level and returns Result.fail(e.getCode(), e.getMessage()).
Validation exceptions : @ExceptionHandler(MethodArgumentNotValidException.class) extracts field error messages via
getBindingResult().getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(", ")), logs at warn, returns Result.fail(ErrorCode.PARAM_ERROR.getCode(), message).
Illegal argument exceptions : @ExceptionHandler(IllegalArgumentException.class) logs at warn, returns HTTP 400 with the exception message.
Catch-all fallback : @ExceptionHandler(Exception.class) logs at error with full stack trace ( log.error("系统未知异常: ", e)), returns generic 500 Result.fail(500, "系统繁忙,请稍后再试") without exposing internal details.
Best Practices & Advanced Tips
Exception Classification : Handle specific exception types rather than catching everything with Exception.class to return precise error information.
Logging Strategy :
Business exceptions → warn level (user errors, rule violations).
System exceptions → error level with full stack trace ( log.error("...", e)) for debugging.
Security : Never return raw stack traces to the frontend when catching Exception.class; doing so leaks database structure, internal paths, and other sensitive data.
Result: Clean Controllers
After applying the global handler, the createUser endpoint reduces to:
@PostMapping("/user")
public Result<User> createUser(@Valid @RequestBody UserDTO userDTO) {
// Business logic, no try-catch needed
User user = userService.createUser(userDTO);
return Result.success(user);
}Controllers stay focused on business flow, readability improves, and maintenance becomes trivial when response formats evolve.
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.
Xiaolin Talks Programming
Focuses on sharing original technical insights. Senior architect at a top tech company with years of experience in technical architecture and management, and extensive interview experience. Offers one-on-one technical coaching, guiding you from beginner to architecture design to technical management. Follow for free learning resources. Free one-on-one interview coaching to help you land offers quickly.
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.
