How to Implement a Global Exception Handler in Spring Boot
This guide explains why a unified exception handling mechanism is essential in Spring Boot applications and provides step‑by‑step code examples for creating a standard response class, custom exception types, an error enumeration, and a @RestControllerAdvice‑based global handler, complete with test screenshots.
Why a Global Exception Handler?
In Spring Boot projects, repetitive try‑catch‑finally blocks clutter the code and reduce readability. Defining a unified exception handling component lets business layers focus on core logic while all errors are processed consistently.
1. Unified Response Class (AjaxResult)
public class AjaxResult {
// Whether the request succeeded
private Boolean success;
// Status code
private Integer code;
// Message
private String msg;
// Data payload
private Object data;
public AjaxResult() {}
public AjaxResult(Boolean success, Integer code, String msg, Object data) {
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
public static AjaxResult defineError(BusinessException de) {
AjaxResult result = new AjaxResult();
result.setSuccess(false);
result.setCode(de.getErrorCode());
result.setMsg(de.getErrorMsg());
result.setData(null);
return result;
}
public static AjaxResult otherError(ErrorEnum errorEnum) {
AjaxResult result = new AjaxResult();
result.setMsg(errorEnum.getErrorMsg());
result.setCode(errorEnum.getErrorCode());
result.setSuccess(false);
result.setData(null);
return result;
}
// getters and setters omitted for brevity
}2. Custom Exception Class (BusinessException)
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** Error code */
protected Integer errorCode;
/** Error message */
protected String errorMsg;
public BusinessException() {}
public BusinessException(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() { return errorCode; }
public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; }
public String getErrorMsg() { return errorMsg; }
public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; }
}3. Error Enumeration (ErrorEnum)
public enum ErrorEnum {
SUCCESS(200, "成功"),
NO_PERMISSION(403, "你没得权限"),
NO_AUTH(401, "未登录"),
NOT_FOUND(404, "未找到该资源!"),
INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员");
private Integer errorCode;
private String errorMsg;
ErrorEnum(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() { return errorCode; }
public String getErrorMsg() { return errorMsg; }
}4. Global Exception Handler
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/** Handle custom BusinessException */
@ExceptionHandler(value = BusinessException.class)
public AjaxResult bizExceptionHandler(BusinessException e) {
log.error(e.getMessage(), e);
return AjaxResult.defineError(e);
}
/** Handle all other exceptions */
@ExceptionHandler(value = Exception.class)
public AjaxResult exceptionHandler(Exception e) {
log.error(e.getMessage(), e);
return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
}
}5. Testing the Handler
The following screenshots show the JSON response returned by the API when an exception is triggered.
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.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
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.
