You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot中自定义异常对应HTTP响应状态码以在Postman正确展示

自定义异常绑定HTTP状态码实现方案

以下给出两种主流后端框架的可直接落地实现方案:

1. Java Spring Boot 实现

第一步:定义业务异常枚举

统一管理所有自定义异常的状态码、描述信息:

public enum BusinessErrorEnum {
    OLD_AND_NEW_PASSWORD_CAN_NOT_BE_SAME(460, "Old and New Password Can Not Be Same"),
    // 其他自定义异常可直接按格式扩展
    ACCOUNT_NOT_EXIST(461, "Account Does Not Exist"),
    TOKEN_EXPIRED(462, "Login Token Has Expired")
    ;

    private final int code;
    private final String msg;

    BusinessErrorEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

第二步:定义自定义业务异常类

public class BusinessException extends RuntimeException {
    private final int code;
    private final String msg;

    public BusinessException(BusinessErrorEnum errorEnum) {
        super(errorEnum.getMsg());
        this.code = errorEnum.getCode();
        this.msg = errorEnum.getMsg();
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

第三步:配置全局异常处理器

统一捕获自定义异常,封装为指定格式的HTTP响应返回:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", e.getCode());
        responseBody.put("msg", e.getMsg());
        // 直接注入自定义状态码到HTTP响应头
        return new ResponseEntity<>(responseBody, HttpStatus.valueOf(e.getCode()));
    }
}

业务侧使用方式

需要触发异常时直接调用即可,Postman会返回对应460状态码和提示信息:

throw new BusinessException(BusinessErrorEnum.OLD_AND_NEW_PASSWORD_CAN_NOT_BE_SAME);

2. Python FastAPI 实现

第一步:定义自定义异常类与常量

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class BusinessException(Exception):
    def __init__(self, code: int, msg: str):
        self.code = code
        self.msg = msg

# 封装为常量方便业务直接调用
OLD_AND_NEW_PASSWORD_CAN_NOT_BE_SAME = BusinessException(460, "Old and New Password Can Not Be Same")
ACCOUNT_NOT_EXIST = BusinessException(461, "Account Does Not Exist")

第二步:注册全局异常处理器

app = FastAPI()

@app.exception_handler(BusinessException)
async def business_exception_handler(request: Request, exc: BusinessException):
    return JSONResponse(
        status_code=exc.code,
        content={"code": exc.code, "msg": exc.msg}
    )

业务侧使用方式

raise OLD_AND_NEW_PASSWORD_CAN_NOT_BE_SAME

注意:自定义HTTP状态码建议选择4xx区间未被标准HTTP协议占用的码段,避免和网关、代理层的默认规则冲突。

内容的提问来源于stack exchange,提问作者Alyan Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:54:05