Try/Catch and Displaying Custom Messages in Collection Runner

I have a request to a service that is expected to return a status of 200, but can sometimes return a 400 if that service is not currently available.

My tests currently return the failed status, but I would rather the error message displayed in the Collection Runner be custom or point out “service not available” instead of the standard 400 error.

Is there a way to do this in the Test that is passed to the Runner? Would a Try / Catch function be applicable?

Hey @SKSG

Welcome to the community :wave:

Shouldn’t that be returning a 503 Service Unavailable rather than a 400?

Just trying to understand the context and the test approach you currently have in place. :grin:

Sorry, when I say “service not available”, I should clarify that the request I am making technically connects, but is not being allowed. I’m working within a CMS-like admin that marks certain services unavailable at times. I just want to clarify in the Collection Runner that while the actual request-response works, our admin setting has prevented a proper response from being returned back.

hi @SKSG

You’ve got more-or-less complete freedom as to what you want your tests to report, below are a couple of examples

const x = Math.random(); console.log('x=' + x);

try{
    pm.expect(x).to.be.below(0.5,"was not below 0.5");
    pm.test("Pass - it was less than 0.5", () => true); // this will only execute if no exception raised
}catch(e){
    pm.test("FAIL - it was more than 0.5", () => {throw new Error(e.message)}); 
}

// alternatively
if(x < 0.5) {
    pm.test("Pass - it was less than 0.5", () => true); 
}else{
    pm.test("FAIL - it was more than 0.5", () => {throw new Error("which is too much :-(")}); 
}

Which will show as
image
or
image

Personally, I use this to suppress excessive numbers of passing tests, one per request is enough for me, but I want to show a failure for any one of the checks I perform: it helps me highlight issues without having to weed through all the things that worked to find the one thing that failed.

5 Likes

Thank you! The try -> catch method worked best. I also added an IF statement to the Catch to check if the status was 400. If it was anything else (such as 404), it throws an error message displaying the status code.

2 Likes