【发布时间】:2016-04-18 06:48:23
【问题描述】:
我在 Mongoose 和 Promisify 中有这个
这是预保存条件 - 我检查是否有暂停(超时),如果一切正常,则添加一个
//check if there is a pause for this id
HonkSchema.pre('save', function(next) {
var query = Pause.where({ id: this.id }).findOneAsync()
.then(function(res){
if(res) {
var e = new Error('Not 5 Minutes')
next(e)
}//else {
next()
//}
})
.catch(function(err){
console.log(err)
var err = new Error(err);
next(err);
})
});
//Add pause
HonkSchema.pre('save', function(next) {
Pause.createAsync({id: this.id})
.then(function(res){
next()
})
.catch(function(err){
console.log(err)
var err = new Error(err);
next(err);
})
});
我这样新建一个
// Creates a new Honk in the DB
export function create(req, res) {
Honk.createAsync(req.body)
.then(responseWithResult(res, 201))
.catch(handleError(res, 412));
}
handleError 就是这样做的
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
console.log(err)
res.status(statusCode).send(JSON.stringify(err));
};
}
上面的日志信息给出了这个
{ [Error: Not 5 Minutes] cause: [Error: Not 5 Minutes], isOperational: true }
但是给客户端的错误信息是这样的
{"cause":{},"isOperational":true}
所以我的问题是,如何向客户端发送有意义的消息?
【问题讨论】:
-
FWIW,Mongoose 已经支持 promises 开箱即用。另外,您想究竟返回给客户什么?一个文本字符串,一个 JSON 对象,...?
-
我在想一个带有错误字段的 JSON 对象。我会拿出所有承诺的东西,看看进展如何
标签: node.js mongodb mongoose promise