我正在使用Mongoose(v。3.8.8)更新我的模型「權限」的一些數據。下面是模式:使用Promises處理CastoError與貓鼬
var PermissionSchema = new Schema({
name : {
type: String, required: true, index: true
},
httpVerb : {
type: String, required: true
},
url : {
type: String, required: true
}
});
mongoose.model('Permission', PermissionSchema);
現在我使用的承諾在另一模塊功能:
module.exports.updatePermission = function (id, updatedPermission) {
var conditions = {_id: id};
var promiseUpdate = Permission.update(conditions, updatedPermission).exec();
logger.debug('this line is not executed when CastError occurs');
var promiseFind = promiseUpdate.then(function (permission) {
return Permission.findOne(conditions).exec();
}).then(null, function (error) {
logger.info('CastError does not get in here');
logger.error(error);
//error handled here
});
return promiseFind;
}
當我打電話與這個例子參數功能:
id: 53496a2e1722ff2d1a55a4d2
updatedPermission: {name: 'this is my new name'}
一切正常罰款因爲_id 確實已經存在於集合中。
現在,當我用傳遞的目的下列參數的無效和不存在的_id:
id: 53496a2e1722ff2d1a55a4d22
updatedPermission: {name: 'this is my new name'}
我得到以下異常:
CastError: Cast to ObjectId failed for value "53496a2e1722ff2d1a55a4d22" at path "_id"
at ObjectId.cast (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/schema/objectid.js:116:13)
at ObjectId.castForQuery (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/schema/objectid.js:165:17)
at Query.cast (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:2291:32)
at castQuery (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:2015:18)
at Query.update (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/query.js:1704:21)
at Function.update (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/node_modules/mongoose/lib/model.js:1606:13)
at Object.module.exports.updatePermission (/home/jhon/environment/workspaces/nodejs-workspace/auth/server/app/repository/auth/PermissionRepository.js:50:36)
我期待得到這個錯誤當承諾被拒絕時,也就是updatePermission函數的第二個「then」。
現在的問題是:這是一個貓鼬的錯誤? - 如何在不使用try/catch的情況下處理這個問題?