2017-07-28 138 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 
});