我的前端是iOS移动应用程序,作为后端数据源,我使用简易表。插入/更新脚本代码是用js文件编写的。
但是,如果我的后端代码中出现任何问题,那么移动应用程序现在就可以了解它。任何人都可以指导我如何实现异常处理,以便我可以将异常发送到移动应用程序?
var table = module.exports = require('azure-mobile-apps').table();
var insertMiddleware = function(req,res,next) {
const util = require('util');
var bPromiseRejected = false;
var promises = [], promisesInsert = [], promisesUpdate = [];
var requestItem = req.body;
var tableRecord = req.azureMobile.tables('Table1');
var itemsToInsert = requestItem.ItemsToInsert;
var itemsToUpdate = requestItem.itemsToUpdate;
console.log('Step 1.' );
//delete records array from feature dict
delete requestItem["ItemsToInsert"];
delete requestItem["itemsToUpdate"];
//context.item = requestItem;
if (itemsToInsert) {
promisesInsert = itemsToInsert.map(function(item) {
return tableRecord.insert(item).then (
// Log the fulfillment value
function(val) {
console.log('Step 5: val: ' + val);
return(val);
}
)
.catch (
// Log the rejection reason
function(reason) {
console.log('Step 6. Handle rejected promise ('+reason+') here.');
bPromiseRejected = true;
return("Error: " + reason);
}
);
});
}
if (itemsToUpdate) {
promisesUpdate = itemsToUpdate.map(function(item) {
return tableRecord.update(item).then (
// Log the fulfillment value
function(val) {
console.log('Step 5: val: ' + val);
return(val);
}
)
.catch (
// Log the rejection reason
function(reason) {
console.log('Step 6. Handle rejected promise ('+reason+') here.');
bPromiseRejected = true;
return("Error: " + reason);
}
);
});
}
promises = promisesInsert.concat(promisesUpdate);
console.log('Promises: ' + util.inspect(promises, false, null));
var result = Promise.all(promises)
.then(function(arrVals) {
//found an error in a promise
console.log('Promise completed. Vals: ' + JSON.stringify(arrVals));
var arrRet = [];
for(var ind in arrVals) {
var val = arrVals[ind];
//if val is a string error, don't do anything
console.log('Typeof Val: ' + typeof(val))
if (typeof(val) === 'string') {
console.log("Already Inserted. Skipping.Val: " + val);
continue;
} else {
console.log("Item Inserted. Adding to Array. Val: " + val);
arrRet.push(val)
}
}
var result = {id:"Success", items: arrRet};
console.log('All Records Inserted: ' + JSON.stringify(result));
return res.end(JSON.stringify(result));
}
)
.catch(
function(reason) {
var retVal = { id: 'ERROR', reason: reason };
console.error("Error: Promise Final.In catch. Reason: " + reason);
res.end(JSON.stringify(retVal));
console.log('After 400 submitted');
}
);
return result;
}
table.insert.use(insertMiddleware, table.operation);
table.insert(function (context) {
return context.execute();
});