How to catch error message when a request fails?

Hi,

my test sends a request and validate code status to be one of 200 or 204.
When it fails the code status could anything like 400,404,500,504…etc
And there will be an error message too.
How can i catch the error message with its code status?

In my case the problem is:
when the request pass the response is empty but i receive a status code 204 or 200.
When the request fails the response has html format if status code is 503
If status is 404 the reponse is in json
So depending the type of errors the reponse body is not the same.
I dont know all type of errors the request could return.

So i just want the tests get 200 or 204 when it passes.
and when the test fails i need to catch all errors and print it in console.log()

Thank you

Hello there, can you provide us an example of request/response and your test scripts

Hi there welcome to the community :smiley:

you can catch assertion errors using try catch block


pm.test("failing test", () => {

    try {

        pm.expect(1).to.eq(2)

    } catch (a) {

        console.log(a)

    }

})

but i am sure there will be better way to test your use case , please add an example as @khan_aktas mentioned

postman uses chai assertions , so you can use any of the chai assertion library methods

https://www.chaijs.com/api/bdd/

3 Likes

Hi,
thank you for your answer.

i tried the code below.
It works:
if code is 201 or 200 then it says succes
if code is not 201 or 200 then it get response from json response

If code is 504 it works if i remove else on the last section of the code.
if (pm.expect(pm.response.code).to.be.not.oneOf([500,504,409,404])){

const $ = cheerio.load(pm.response.text());
//console.log("error html ");
pm.test(“html error message”, () => {
console.log($(“body”).text());
pm.expect.fail(‘Failed’);
});
}

Now if the code returns 201 or 200
it says success
but it returns: Check the html error message | AssertionError: Test failed

because i added a ELSE IF

What i want is:
if the code returns 201 or 200 the code should stop there by telling success and it should not run the reste of the code to search for html response because there is no html response when code is 200 or 201
The html response comes only when code is 504 or 409…

if([201,200].includes(pm.response.code)){
console.log (“success”);
}
else {
console.log(" error ");
pm.test(“error message”, () => {
jsonData = pm.response.json();
console.log(“Response value is:”+jsonData.message)
console.log(“Response value is:”+jsonData.httpStatus)
pm.expect.fail(‘Failed’);
});
}

else if (pm.expect(pm.response.code).to.be.not.oneOf([500,504,409,404])){
const $ = cheerio.load(pm.response.text());
//console.log("error html ");
pm.test(“html error message”, () => {
console.log($(“body”).text());
pm.expect.fail(‘Failed’);
});
}