Backend Development 5 min read

Implementing a Global Exception Handler in Spring Boot

This article explains how to replace repetitive try‑catch blocks in Spring Boot applications with a unified global exception handling solution by defining a standard AjaxResult response, a custom BusinessException, an error enumeration, and a @RestControllerAdvice handler, enabling clean, extensible error management.

Top Architect
Top Architect
Top Architect
Implementing a Global Exception Handler in Spring Boot

In Spring Boot projects, repetitive try‑catch blocks reduce readability, so a unified global exception handling mechanism is recommended.

First, define a generic AjaxResult class to encapsulate success flag, status code, message and data.

public class AjaxResult {
    //是否成功
    private Boolean success;
    //状态码
    private Integer code;
    //提示信息
    private String msg;
    //数据
    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
}

Second, create a custom BusinessException extending RuntimeException to carry an error code and message.

public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    protected Integer errorCode;
    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; }
}

Third, use an ErrorEnum enumeration to avoid hard‑coded error values.

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; }
}

Finally, implement a @RestControllerAdvice class GlobalExceptionHandler that catches BusinessException and generic Exception , logs the error, and returns an appropriate AjaxResult .

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.defineError(e);
    }
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
    }
}

Integrating these components requires only simple configuration and can be extended for finer‑grained business exceptions, greatly improving code cleanliness and maintainability.

JavaBackend DevelopmentSpring Booterror handlingRESTGlobal Exception Handling
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.