Mastering Global Exception Handling in Spring Boot

This guide explains why excessive try‑catch blocks hurt Spring Boot projects, introduces a unified response class, custom business exception, error enumeration, and a global @RestControllerAdvice handler, providing clean, reusable error handling with sample code and test usage.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Mastering Global Exception Handling in Spring Boot

Preface

When developing a Spring Boot project, handling numerous exceptions with try‑catch blocks leads to redundant code and poor readability.

A global unified exception handler can eliminate the need for business‑layer exception handling.

Why Use This Approach

Simply copy the code into a project and configure it.

Allows fine‑grained extension for custom business exceptions.

Implementation

1. Unified response class

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;
    }
    public Boolean getSuccess() { return success; }
    public void setSuccess(Boolean success) { this.success = success; }
    public Integer getCode() { return code; }
    public void setCode(Integer code) { this.code = code; }
    public String getMsg() { return msg; }
    public void setMsg(String msg) { this.msg = msg; }
    public Object getData() { return data; }
    public void setData(Object data) { this.data = data; }
}

2. Custom business exception

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

3. Error enumeration to 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);

    /** 处理自定义异常 */
    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.defineError(e);
    }

    /** 处理其他异常 */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
    }
}

5. Test controller example

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.business.component.BusinessException;
import com.example.business.component.ErrorEnum;

@Controller
@RequestMapping("test")
public class TestController extends BaseController {

    @RequestMapping("query")
    @ResponseBody
    public Object query() {
        throw new BusinessException(ErrorEnum.NO_PERMISSION.getErrorCode(),
                ErrorEnum.NO_PERMISSION.getErrorMsg());
    }
}

Resulting JSON response example:

Result example
Result example
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 DevelopmentException HandlingSpring Boot
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.