Proper way to catch exception from JSON.parse

后端 未结 5 1954
轻奢々
轻奢々 2020-12-02 07:13

I’m using JSON.parse on a response that sometimes contains a 404 response. In the cases where it returns 404, is there a way to catch an exception and then exec

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 08:06

    This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

    Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
        console.log(json);
    }).catch(err => {
        console.log(err);
    });
    

提交回复
热议问题