ubuntu

Ubuntu Postman如何处理错误响应

小樊
46
2025-11-18 13:24:14
栏目: 智能运维

Ubuntu 上 Postman 处理错误响应的实用流程

一 快速判定错误类型

二 在 Tests 脚本中标准化识别与断言

// Tests
pm.test("Status is 2xx", () => {
    pm.expect(pm.response.code).to.be.within(200, 299);
});

pm.test("Content-Type is JSON", () => {
    pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});

pm.test("Response time < 500ms", () => {
    pm.expect(pm.response.responseTime).to.be.below(500);
});
// Tests
let json;
try {
    json = pm.response.json();
} catch (e) {
    json = null;
}

if (json) {
    // 示例:按常见 API 错误字段做判定
    if (json.error) {
        pm.test("Has error field", () => pm.expect(json.error).to.be.a("string"));
    }
    if (json.message) {
        pm.test("Has message field", () => pm.expect(json.message).to.be.a("string"));
    }
    if (json.code !== undefined) {
        pm.test("Has code field", () => pm.expect(Number.isInteger(json.code)).to.be.true);
    }
} else {
    // 非 JSON 时,直接对文本做包含性检查
    pm.test("Response is not JSON", () => {
        pm.expect(pm.response.text()).to.be.a("string");
    });
}
// Tests
let json = {};
try { json = pm.response.json(); } catch (e) {}

const errorInfo = {
    status: pm.response.code,
    statusText: pm.response.statusText,
    url: pm.request.url.toString(),
    method: pm.request.method,
    time: pm.response.responseTime,
    body: json || pm.response.text()
};

pm.environment.set("lastError", JSON.stringify(errorInfo, null, 2));
// Pre-request Script
const token = pm.environment.get("token");
if (token) {
    pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
}

三 常见 HTTP 错误码的快速处理建议

状态码 含义 常见原因 排查要点
400 Bad Request 参数缺失/格式错误 核对请求参数、请求体 JSON 语法、Content-Type
401 Unauthorized 未认证或令牌失效 检查 Authorization 头、Token 是否过期、作用域是否匹配
403 Forbidden 权限不足 核对账号权限、API 密钥权限、访问策略
404 Not Found 路径错误或服务未部署 核对 URL 路径、端口、路由是否发布
408 Request Timeout 服务器处理慢或客户端超时过短 增大 Timeout、优化服务端处理
500 Internal Server Error 服务器代码异常 查看服务端日志、复现并定位根因
502/503 Bad Gateway / Service Unavailable 网关/上游不可用、服务未启动或端口未开放 检查服务是否监听、反向代理/网关配置、服务器端口与防火墙
504 Gateway Timeout 上游响应超时 优化上游性能、调整网关超时阈值

四 网络与证书层面的排查要点

五 自动化与持续集成中的错误判定

# 安装 Newman
npm install -g newman

# 运行并生成 CLI 与 HTML 报告
newman run ./API-Tests.postman_collection.json \
  -e ./env.postman_environment.json \
  --reporters cli,html \
  --reporter-html-export report.html
name: Postman API Tests
on:
  push:
    branches: [ main ]

jobs:
  run-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: postman/newman-action@v1
        with:
          collection: ./API-Tests.postman_collection.json
          environment: ./env.postman_environment.json
          reporters: cli,html
          htmlReporter: ./report.html

0
看了该问题的人还看了