从以下代码:
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];
}
}
});
我收到以下错误:
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)
基本上,如果JSON为空或null
,我想发出警告,但我无法做到。
我怎样才能发现这个错误?
答案 0 :(得分:1)
您的Javascript无效,由于以下原因,该脚本甚至无法运行:if (model == null {
使用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];
});
或者,测试一下blog [0]是否存在,尽管它会减少错误:
BlogApp.query.blog.equalTo("objectId", url).find().then(function(blog) {
if (!blog[0]) {
Materialize.toast('This object no long exists!', 4000, 'red');
return;
}
答案 1 :(得分:0)
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];
}
}
});