Master Global Exception Handling in Spring Boot: Unified Error Responses
This article explains how to replace repetitive try‑catch blocks in Spring Boot with a unified global exception handler, introducing a standard AjaxResult wrapper, custom BusinessException, an error enumeration, and a @RestControllerAdvice that returns consistent JSON error responses across the application.
Introduction
When developing a Spring Boot application, handling numerous try‑catch blocks across layers leads to redundant code and poor readability. A unified global exception handler allows business code to avoid explicit exception handling.
Why Use It
Copy the code into the project and enable it with minimal configuration.
Flexibly extend to finer‑grained business exceptions.
1. Unified Result Wrapper
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() {}
// Constructor for custom result
public AjaxResult(Boolean success, Integer code, String msg, Object data) {
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
// Result for custom business exception
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;
}
// Result for other exceptions
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 Business Exception
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 Enum (Avoid Hard‑Coding)
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 business exception
@ExceptionHandler(BusinessException.class)
public AjaxResult bizExceptionHandler(BusinessException e) {
log.error(e.getMessage(), e);
return AjaxResult.defineError(e);
}
// Handle all other exceptions
@ExceptionHandler(Exception.class)
public AjaxResult exceptionHandler(Exception e) {
log.error(e.getMessage(), e);
return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
}
}5. Test Result
The API returns a unified JSON structure containing success, code, msg, and data fields, regardless of whether the exception is a custom business exception or a generic error.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
