2017-07-28 116 views
0

我有一个异步函数异步调用函数

async function getPostAsync() { 
    const post = await Post.findById('id'); 

    // if promise was successful, 
    // but post with specific id doesn't exist 
    if (!post) { 
    throw new Error('Post was not found'); 
    } 

    return post; 
} 

我打电话与

app.get('/', (req, res) => { 
    getPostAsync().then(post => { 
    res.json({ 
     status: 'success', 
    }); 
    }).catch(err => { 
    res.status(400).json({ 
     status: 'error', 
     err 
    }); 
    }) 
}); 

但功能我刚刚收到

{ 
    "status": "error", 
    "err": {} 
} 

我期望要么得到错误Post was not found或连接或类似的错误,但变量err只是我的catch声明中的一个空对象。

+0

不'Post.findById'返回一个承诺? –

+0

是的。它来自'mongoose' – Jamgreen

+1

尝试在你的catch块中发送完整的错误对象:'err:JSON.stringify(err)',可能错误对象不包含消息,因为'err'是空字符串在一个回应。 – alexmac

回答

0

考虑以下几点:

let e = Error('foobar'); 
console.log(JSON.stringify(e)) 

此输出{},就像你的情况。这是因为错误不能序列化为JSON。

相反,试试这个:

res.status(400).json({ 
    status : 'error', 
    err : err.message // `String(err)` would also work 
});