# Can't log "Type error cannot read property"

**URL:** <https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173>\
**Category:** OSS Support\
**Created:** [November 29, 2022, 7:06pm UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173 "2022-11-29T19:06:01Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![rodyb](https://avatars.discourse-cdn.com/v4/letter/r/58f4c7/32.png) [@rodyb](https://community.grafana.com/u/rodyb)\
**Post date:** [November 29, 2022, 7:06pm UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/1 "2022-11-29T19:06:01Z")

</div>

Hi team,

I am running into an issue. Apparently some request does not seem to fulfil (highly likely on our app’s side)

```auto
ERRO[0033] TypeError: Cannot read property 'id' of undefined

```

I tried to see if it could be logged and also added --http-debug to the run but nothing shows :

- [Why build didn't fail at TypeError in K6 - #2 by nedyalko](https://community.grafana.com/t/why-build-didnt-fail-at-typeerror-in-k6/95641/2)
- [TypeError: Cannot read property '0' of undefined · Issue #653 · grafana/k6 · GitHub](https://github.com/grafana/k6/issues/653)

It looks to me, the id im trying to use is not ready from application side, but I do want to make sure it is indeed the application. Statuscode checks all seem passed. However I can’t seem to log it properly to make sure what statuscode it returns(in the console).

Is it possible when a typeError occurs, to add it into the final results overview?  
What would be your recommended approach in this case?

Thanks,

Rody

---

<div class="post-metadata">

**Author:** ![oleiade](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/oleiade/32/35836_2.png) [@oleiade](https://community.grafana.com/u/oleiade)\
**Post date:** [November 30, 2022, 8:43am UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/3 "2022-11-30T08:43:32Z")

</div>

Hi @rodyb

Could you please post an example of a script (anonymized) that illustrates the error scenario you’re describing, it would be really hard for me to help you in a productive manner otherwise 🙂

Cheers 🙇‍♂️

---

<div class="post-metadata">

**Author:** ![rodyb](https://avatars.discourse-cdn.com/v4/letter/r/58f4c7/32.png) [@rodyb](https://community.grafana.com/u/rodyb)\
**Post date:** [November 30, 2022, 10:11am UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/4 "2022-11-30T10:11:22Z")

</div>

Hi @oleiade,

Thanks for your quick reply.

```auto
export function setup() {
    token = authenticateOAUTH();

    return {
        'token': token,
    };
}

export default function (authenticated) {
    let session = new Httpx({
        headers: {
            'Authorization': 'Bearer ' + authenticated.token,
            'Content-Type': 'text/plain'
        },
    });

    group('Organize - Create a Metaproperty and an option ', function () {
        data = `data={"name": "${random_name + randomIntBetween(1, 5000)}", "type": "select", "label": "${random_name + randomIntBetween(1, 5000)}", "isEditable": "true"}`
        let createNewMetaProperty = session.post(`${ __ENV.URL}/api/${__ ENV.TARGET}/metaproperties`, data, {tags: {name: "Create metaproperty"}});

        id = createNewMetaProperty.json()['id']

        check(createNewMetaProperty, {
            'Metaproperty Status code 201': (r) => r.status === 201,
            'Id exists with correct name': (r) => r.json()['id'].includes(id) || errorRate.add(1),
            'ID not empty' : (r) => r.json()['id'] !== null,
            'Metaproperty created': (r) => r.json()['message'] === 'Created',
        })

        var metapropertyFound = pollForMetaproperty(id, random_name, authenticated.token)
        check(metapropertyFound, {
            'Metaproperty is found': (r) => r.status === 200 || errorRate.add(1),
            'Name of metaproperty has correct name': (r) => r.json()['name'].includes(random_name)
        });

        session.addHeader('Content-Type', 'application/x-www-form-urlencoded');

        data = {'data': `{"name": "${random_name + name + randomIntBetween(1, 5000)}"}`, 'options': `{"name": "${random_name + randomIntBetween(1, 5000)} + OPTION NAME"}`}
        let addOption = session.post(`${ __ENV.URL}/api/${__ ENV.TARGET}/metaproperties/${id}/options/`, data, {tags: {name: "Create Metaproperty option"}});

        check(addOption, {
            'Option Status code 201': (r) => r.status === 201 || errorRate.add(1),
            'Option is created': (r) => r.json()['message'] === 'Created'
        });
    });

    group('Organize - Modify Metaproperty option', function () {
        session.addHeader('Content-Type', null);

        let getMetaPropertyToValidateOption = session.get(`${ __ENV.URL}/api/${__ ENV.TARGET}/metaproperties/${id}`); //<<<-- based on the typeError it gives an error somewhere here I believe. 
        optionId = getMetaPropertyToValidateOption.json()['options'][0]['id'] 

        check(getMetaPropertyToValidateOption, {
            'Validate name is present' : (r) => r.json()['options'][0]['displayLabel'].includes(random_name + name),
            'Option Id is not empty' : (r) => r.json()['options'][0]['id'] !== null
        })

```

Looking forward to your reply! Thanks in advance!

---

<div class="post-metadata">

**Author:** ![oleiade](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/oleiade/32/35836_2.png) [@oleiade](https://community.grafana.com/u/oleiade)\
**Post date:** [November 30, 2022, 4:59pm UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/5 "2022-11-30T16:59:15Z")

</div>

Thanks a lot for posting your example script 👍 That’s really helpful!

You seem to be accessing `'id'` in a variety of places, have you been able to isolate which of those throw a `TypeError`?

The `json()` method of [HTTP Response](https://k6.io/docs/javascript-api/k6-http/response/) returns either an `Object` or an `Array`, thus what k6 is reporting here, is a JS error happening because you’re trying to access the `id` property on a value that is undefined. From what I see in your code, that means that in the case of `getMetaPropertyToValidateOption.json()['options'][0]['id']` for instance, it could be that the result of `getMetaPropertyToValidateOption.json()['options'][0]` is undefined (thus likely either options is undefined in your response’s body, or the array is empty and does not have an index `[0]`).

To track where the error happens, I would wrap every call you make which tries to access `['id']` with a `try/catch` block printing a dedicated message to the terminal, to find out what happens:

```javascript
try {
    optionId = getMetaPropertyToValidateOption.json()['options'][0]['id']
} catch (err) {
    console.log(`unable to get meta property to validate option, reason: ${JSON.stringify(err)}, with body ${JSON.stringify(getMetaPropertyToValidateOption.json()}}`

```

Let me know if that helps 🙇‍♂️

---

<div class="post-metadata">

**Author:** ![rodyb](https://avatars.discourse-cdn.com/v4/letter/r/58f4c7/32.png) [@rodyb](https://community.grafana.com/u/rodyb)\
**Post date:** [December 1, 2022, 7:32am UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/6 "2022-12-01T07:32:29Z")

</div>

@oleiade  
Thank you!

I see that in that point of time, the server is still processing the options. It’s empty.  
This really helped! Much appreciated 🙂

---

<div class="post-metadata">

**Author:** ![oleiade](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/oleiade/32/35836_2.png) [@oleiade](https://community.grafana.com/u/oleiade)\
**Post date:** [December 1, 2022, 8:29am UTC](https://community.grafana.com/t/cant-log-type-error-cannot-read-property/96173/7 "2022-12-01T08:29:33Z")

</div>

I’m glad I could be of help 👏
