# Unable to store error reponse 401 as variable

**URL:** <https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851>\
**Category:** Help Hub\
**Tags:** variables, collections, json\
**Created:** [August 22, 2023, 6:21pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851 "2023-08-22T18:21:55Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![research-technolog10](https://avatars.discourse-cdn.com/v4/letter/r/e0b2c6/32.png) [@research-technolog10](https://community.postman.com/u/research-technolog10)\
**Post date:** [August 22, 2023, 6:21pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/1 "2023-08-22T18:21:55Z")

</div>

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);

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [August 22, 2023, 6:32pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/2 "2023-08-22T18:32:55Z")

</div>

Hey @research-technolog10 👋

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. 🏆

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. 😅

---

<div class="post-metadata">

**Author:** ![research-technolog10](https://avatars.discourse-cdn.com/v4/letter/r/e0b2c6/32.png) [@research-technolog10](https://community.postman.com/u/research-technolog10)\
**Post date:** [August 22, 2023, 6:46pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/3 "2023-08-22T18:46:49Z")

</div>

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.

```auto
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());
        }
    });
}

```

---

<div class="post-metadata">

**Author:** ![michaelderekjones](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/michaelderekjones/32/14819_2.png) [@michaelderekjones](https://community.postman.com/u/michaelderekjones)\
**Post date:** [August 23, 2023, 9:22am UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/4 "2023-08-23T09:22:38Z")

</div>

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.

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

```

[defining-variables-in-scripts | Postman Learning Center](https://learning.postman.com/docs/sending-requests/variables/#defining-variables-in-scripts)

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.

---

<div class="post-metadata">

**Author:** ![research-technolog10](https://avatars.discourse-cdn.com/v4/letter/r/e0b2c6/32.png) [@research-technolog10](https://community.postman.com/u/research-technolog10)\
**Post date:** [August 27, 2023, 11:23pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/5 "2023-08-27T23:23:30Z")

</div>

Thank you. This worked.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [September 3, 2023, 11:24pm UTC](https://community.postman.com/t/unable-to-store-error-reponse-401-as-variable/50851/6 "2023-09-03T23:24:24Z")

</div>

Closed on September 3, 2023, 11:24pm UTC

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