Linux 上 Postman 处理错误响应的实用流程
一 快速定位与日志
二 在 Tests 中识别并断言错误响应
示例 Tests 脚本(可直接放入请求或集合的 Tests 标签):
// 1) 状态码:预期成功
pm.test("Status code is 2xx", () => {
pm.expect(pm.response.code).to.be.oneOf([200, 201, 204]);
});
// 2) 状态码:预期失败(示例为 400/401/404/500)
pm.test("Status code is error", () => {
const code = pm.response.code;
pm.expect([400, 401, 404, 500]).to.include(code);
});
// 3) JSON 错误结构校验(根据实际字段名调整)
pm.test("Error response has message and code", () => {
const json = pm.response.json();
pm.expect(json).to.have.property("error").that.is.a("object");
pm.expect(json.error).to.have.property("message").that.is.a("string");
pm.expect(json.error).to.have.property("code").that.is.a("number");
});
// 4) 非 JSON 响应:包含关键字即判错
pm.test("Response contains error keyword", () => {
pm.expect(pm.response.text()).to.include("error");
});
// 5) 响应头校验
pm.test("Content-Type is application/json", () => {
pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});
// 6) 响应时间阈值
pm.test("Response time < 500ms", () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});
上述写法基于 Postman 的pm.test / pm.expect与pm.response对象,可校验状态码、头部、Cookie、响应时间与正文内容,并支持 JSON/文本等多种响应格式。
三 常见错误场景与处理建议
unset http_proxy https_proxy或在 Postman 代理设置中清空。四 自动化与持续反馈