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
聲明中的一個空對象。
不'Post.findById'返回一個承諾? –
是的。它來自'mongoose' – Jamgreen
嘗試在你的catch塊中發送完整的錯誤對象:'err:JSON.stringify(err)',可能錯誤對象不包含消息,因爲'err'是空字符串在一個迴應。 – alexmac