Unable to store error reponse 401 as variable

For some reason

I am trying to capture the 401 error response as variable using the Tests script below. The variable will then be reuse in my collections script and tell it to reauthenticate the api. However, the script below only captures and saves 200 response. If I purposely break auth, and 401 response is received, the 401 is not stored as variable. Thoughts?

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable(“resCode”, pm.response.code);

Hey @research-technolog10 :wave:

Welcome to the Postman community! :postman:

Could you elaborate more on the actual flow, please?

You mentioned capturing the response, then something returning a 200 and then using the response to reauthenticate something - It’s all a little confusing and I would like to clarify what you’re usecase is and get you to a solution quickly. :trophy:

Also, can I ask where you got that code snippet from as it’s a mix of old and new syntax and I just wanted to check it isn’t something that we have published somewhere. :sweat_smile:

I have a collection runner that does a GET then a POST. It’s a large data set of a couple thousand rows . After a few hundred rows the server sees my request as spam and returns a 401 challenge.

If I manually reauthenticate (new token) the issue goes away. So as a workaround, in the GET request I want to add the above Test script to store the response code in an environment variable. (eg 200, 401, 503 etc)

In my collection Pre-request Script (below) I check if the code store is not* 200, then reauthenticate. This doesn’t work because nothing other than 200 is saved. I got the code from searching different site for help.

const echoPostRequest = {
  url: 'https://someurl/auth-service/login',
  method: 'POST',
  header: 'Content-Type:application/json',
  body: {
    mode: 'application/json',
    raw: JSON.stringify(
        {
        	password: 'passowrd',
            username: 'usrname'
        })
  }
};

var getToken = true;


if (!pm.environment.get('accessTokenExpiry') || 
    !pm.environment.get('currentAccessToken')) {
    console.log('Token or expiry date are missing')
} 
else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
    console.log('Token is expired')
} 
else if (!pm.environment.get('resCode') === 200) { console.log('reauthenticationg')
} 
else {
    getToken = false;
    console.log('Token and expiry date are all good');
}

if (getToken === true) {
    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            console.log('Saving the token and expiry date')
            var responseJson = res.json();
            pm.environment.set('currentAccessToken', responseJson.accessToken)
    
            var expiryDate = new Date();
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.claims.exp);
            pm.environment.set('accessTokenExpiry', expiryDate.getTime());
        }
    });
}

I’ve just checked a few of my saved requests that use authentication.

I’ve invalidated the requests, so they return 400, 401, etc.

For each, the status code is returned within pm.response.code and it does capture the 400 and 401 codes. Try console logging it first to confirm and use the pm function to set the environment variable.

console.log(pm.response.code);
pm.environment.set("resCode", pm.response.code);

defining-variables-in-scripts | Postman Learning Center

It’s also worth noting that I’m authenticating against Microsoft which returns a JSON body with those codes with more information that could also be used.

I’m not sure how this will work with a pre-request script on its own though. You will also need to use the tests tab and setNextRequest() to rerun the same request again but be careful that you don’t get an indefinite loop.

1 Like

Thank you. This worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.