Ad

Splitting Variable With Json Leads To Uncaught TypeError

- 1 answer

I'm trying to split the content of a variable pickerValue, so that the end result only shows "eosptest2"

The console.log shows pickerValue: i:0#.w|opmain\eosptest2;

The problem is that I get an Uncaught TypeError: Cannot read property '0' of undefined at the following line:

return json[0].id.split("\\")[1];

This is the function:

function getUserNameFromPeoplePicker(pickerValue, returnType) {

    if (checkNull(pickerValue) == "") {
        return "";
    }

    var json;

    try {
        json = JSON.parse(pickerValue);
    } catch (err) {
        return replaceSubstring(pickerValue.split("\\")[1], ";", "");
    } finally {
        switch (returnType) {
            case "label":
                console.log("json[0].label: " + json[0].label);
                return json[0].label;
                break;

            case "id":
                console.log("pickerValue: " + pickerValue);
                // console.log("Json id split: " + json[0].id.split("\\")[1]);
                return json[0].id.split("\\")[1];

            default:

                return replaceSubstring(pickerValue.split("\\")[1], ";", "");
                //return replaceSubstring(json[0].value.split("\\")[1], ";", "");
                break;
        }
    }
}

To test it, I replaced the return statement with return "eosptest2" and it worked fine, but I don't know what exactly needs to be changed.

How can one fix this issue?

Ad

Answer

You're running your switch cases under the assumption that the json variable is always defined, but if the catch() block ran, that means that your json variable will be undefined:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // an error got caught, this block runs regardless, and now json is undefined
        console.log(`json variable: ${json}`);
    }
}

const result = example(";");
console.log(result);

What you're also assuming is that if you have a return statement in the catch() block, this will stop the finally block from executing, but that's not true. The finally block will execute its code, and only then will it return some statement.

Also note that if you have a return statement in both the catch and finally block, the finally return statement will take priority over the other:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // but this return statement takes priority over catch
        return "finally";
    }
}

const result = example(";");
console.log(result);

Ad
source: stackoverflow.com
Ad