Martin Erlic
Martin Erlic

Reputation: 5665

How to handle Uncaught TypeError on undefined JSON?

From the following code:

    BlogApp.query.blog.equalTo("objectId", url).find().then(function(blog) {
        var model = blog[0];
        model = model.toJSON();

        if (model == null {
                Materialize.toast('This object no long exists!', 4000, 'red');
            } else {

                BlogApp.fn.renderView({
                    View: BlogApp.Views.Blog,
                    data: {
                        model: model
                    }
                });

                BlogApp.blog = blog[0];
            }
        }
    });

I get the following error:

blog.js:1119 Uncaught TypeError: Cannot read property 'toJSON' of undefined
    at blog.js:1119
    at wrappedResolvedCallback (parse-1.2.19.js:3762)
    at parse-1.2.19.js:3713
    at Array.forEach (<anonymous>)
    at Object._.each._.forEach [as _arrayEach] (parse-1.2.19.js:95)
    at Parse.Promise.resolve (parse-1.2.19.js:3712)
    at Parse.Promise.<anonymous> (parse-1.2.19.js:3766)
    at Parse.Promise.wrappedResolvedCallback (parse-1.2.19.js:3762)
    at Parse.Promise.then (parse-1.2.19.js:3796)
    at wrappedResolvedCallback (parse-1.2.19.js:3765)

Basically, if the JSON is empty or null, I want to issue a warning but I'm not able to do that.

How can I catch this error?

Upvotes: 0

Views: 1480

Answers (2)

codejockie
codejockie

Reputation: 10844

BlogApp.query.blog.equalTo("objectId", url).find().then(function(blog) {
    var model = blog[0];

    if (!model) {
            Materialize.toast('This object no long exists!', 4000, 'red');
        } else {
            model = model.toJSON();

            BlogApp.fn.renderView({
                View: BlogApp.Views.Blog,
                data: {
                    model: model
                }
            });

            BlogApp.blog = blog[0];
        }
    }
});

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370619

Your Javascript is invalid, the script shouldn't even run because of: if (model == null {

Use try-catch.

BlogApp.query.blog.equalTo("objectId", url).find().then(function(blog) {
  const model = blog[0];
  let jsonModel;
  try {
    jsonModel = model.toJSON();
  } catch (e) {
    Materialize.toast('This object no long exists!', 4000, 'red');
    return;
  }
  BlogApp.fn.renderView({
    View: BlogApp.Views.Blog,
    data: {
      model: jsonModel
    }
  });
  BlogApp.blog = blog[0];
});

Alternatively, test to see if blog[0] exists at the beginning, though it'll catch fewer errors:

BlogApp.query.blog.equalTo("objectId", url).find().then(function(blog) {
  if (!blog[0]) {
    Materialize.toast('This object no long exists!', 4000, 'red');
    return;
  }

Upvotes: 1

Related Questions