錯誤處理
大多數Parse JavaScript函數使用具有回調的對象報告其成功或失敗,類似于Backbone的“options”對象。這兩個主要回調是success和error。
success回調只會在操作完成且沒有錯誤時被調用。通常,它的參數是save或get方法的Parse.Object、或find方法的Parse.Object數組。
error回調在通過網絡與Parse Cloud進行交互時發生任何錯誤時被調用。這些錯誤可能是連接到Parse Cloud出錯或執行請求操作時出錯。
我們來看一個例子。在下面的代碼中,我們嘗試獲取一個不存在的對象objectId。Parse Cloud將返回一個錯誤——以下是在回調中如何正確處理它的示例:
var query = new Parse.Query(Note);
query.get("aBcDeFgH", {
success: function(results) {
// This function will *not* be called.
alert("Everything went fine!");
},
error: function(model, error) {
// This will be called.
// error is an instance of Parse.Error with details about the error.
if (error.code === Parse.Error.OBJECT_NOT_FOUND) {
alert("Uh oh, we couldn't find the object!");
}
}
});
也可能因為設備無法連接到Parse Cloud而導致查詢失敗。回調依然相同,只是還需要一些額外的代碼來處理這種情況:
var query = new Parse.Query(Note);
query.get("thisObjectIdDoesntExist", {
success: function(results) {
// This function will *not* be called.
alert("Everything went fine!");
},
error: function(model, error) {
// This will be called.
// error is an instance of Parse.Error with details about the error.
if (error.code === Parse.Error.OBJECT_NOT_FOUND) {
alert("Uh oh, we couldn't find the object!");
} else if (error.code === Parse.Error.CONNECTION_FAILED) {
alert("Uh oh, we couldn't even connect to the Parse Cloud!");
}
}
});
對于像save和signUp這類會影響特定Parse.Object對象的方法,error回調函數的第一個參數是對象本身,第二個參數是Parse.Error對象。這是為了與類Backbone的框架兼容。
對于Parse.Error錯誤代碼列表,請參見“錯誤代碼Error Codes”章節,或參見JavaScript API Parse.Error的Parse.Error部分。