</>

Technology

Postman

Difficulty

Intermediate

Interview Question

How do you handle error responses in Postman tests?

Answer

Handling Error Responses in Postman Tests

Testing error responses is just as important as testing success scenarios. Here''s how to validate them properly.

Testing 4xx Client Errors

400 Bad Request

JavaScript
// Send request without required fields
pm.test("Returns 400 for missing fields", function () {
    pm.response.to.have.status(400);
});

pm.test("Error message is correct", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.error).to.include("required");
});

401 Unauthorized

JavaScript
// Send request without auth token
pm.test("Returns 401 when no token", function () {
    pm.response.to.have.status(401);
});

pm.test("Error message mentions authorization", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.message).to.be.oneOf([
        "Unauthorized",
        "Invalid credentials",
        "Token is missing"
    ]);
});

404 Not Found

JavaScript
pm.test("Returns 404 for non-existent resource", function () {
    pm.response.to.have.status(404);
});

pm.test("Error body is correct", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("error");
    pm.expect(jsonData.error).to.include("not found");
});

Testing 5xx Server Errors

JavaScript
pm.test("Handle 500 gracefully", function () {
    // If server error, log it but don''t fail the whole suite
    if (pm.response.code === 500) {
        console.log("Server error:", pm.response.text());
        pm.expect.fail("Server returned 500 - investigate");
    }
});

Conditional Validation Based on Status

JavaScript
const statusCode = pm.response.code;

if (statusCode === 200) {
    pm.test("Success response has data", function () {
        const jsonData = pm.response.json();
        pm.expect(jsonData.data).to.exist;
    });
} else if (statusCode === 404) {
    pm.test("Not found has error message", function () {
        const jsonData = pm.response.json();
        pm.expect(jsonData.error).to.exist;
    });
} else {
    pm.test("Unexpected status code: " + statusCode, function () {
        pm.expect.fail("Unexpected status code");
    });
}

Error Response Schema Validation

JavaScript
pm.test("Error response has correct structure", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.all.keys("error", "code", "message");
    pm.expect(jsonData.code).to.be.a("number");
    pm.expect(jsonData.message).to.be.a("string");
});

Follow AutomateQA

Related Topics