2 Developer
2 Developer

Reputation: 257

Unable to handle Unexpected error in angular 2+

here I am trying a functionality there will be a file upload where I can upload a JSON file and that data will be posted to a textarea and also we can also type the JSON structure in that here after pressing the button the data will be transferred to another textarea which will remove all the white space and new lines etc . all these worked fine but here my issue is If I enter normal text and press enter then it is giving me error like unexpected token

below is my JSON structure I am using

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
]

below is my stack blitz code

https://stackblitz.com/edit/angular-zgyxet

If I enter the JSON structure it is working fine but if I enter plain text it is giving error how to handle this error so that I can give an alert to a user.

Upvotes: 0

Views: 151

Answers (1)

Prijesh Meppayil
Prijesh Meppayil

Reputation: 540

The error message is getting from JSON.parse() method because we can't parse a normal string to JSON(ie which are not in the JSON format).

Please put your JSON.parse() method in a try/catch block as below :

test() {
    var data = this.TextData;
    var dataInfo = data.replace(/\s+/g, '').trim();
    var info = '';
    try {
        var info = JSON.parse(dataInfo);
    } catch(e) {
        alert('JSON parse error');
    }

    this.TextData1 = info;
}

Upvotes: 2

Related Questions