Master Global Exception Handling in Spring Boot: A Complete Guide

This article explains how to create a unified response class, define custom exception and error‑enum types, and implement a global exception handler in Spring Boot, enabling clean error handling, reduced boilerplate, and flexible business‑specific extensions.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Master Global Exception Handling in Spring Boot: A Complete Guide

Preface

During Spring Boot development, handling numerous try…catch…finally blocks across MVC layers leads to redundant code and reduced readability. Defining a global unified exception handler allows business layers to avoid repetitive error handling.

Benefits

Copy the code into the project and enable it with simple configuration.

Flexibly extend to finer‑grained business‑specific exceptions.

1. Unified Response Class (AjaxResult)

AjaxResult diagram
AjaxResult diagram
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() {}

    // Custom constructor
    public AjaxResult(Boolean success, Integer code, String msg, Object data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // Factory method for business exceptions
    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;
    }

    // Factory method for other errors
    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)

BusinessException diagram
BusinessException diagram
public class BusinessException extends RuntimeException {
    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; }
}

3. Error Enum (ErrorEnum)

ErrorEnum diagram
ErrorEnum diagram
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 (GlobalExceptionHandler)

GlobalExceptionHandler diagram
GlobalExceptionHandler diagram
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // Handle custom business exceptions
    @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

Test screenshot
Test screenshot

The test demonstrates that the unified response format is returned correctly for both successful and error scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentSpring Bootcustom-exceptionglobal exception handlingAjaxResultError Enum
Java Backend Technology
Written by

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!

0 followers
Reader feedback

How this landed with the community

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.