处理承诺和异步等待功能

Handling promise and async await function

我在node和express中有这个功能

router.post('/', async (req, res) => {
    const playlist = new Playlist({
        song: req.body.song,
        artist: req.body.artist
    })

    try {
        const newPlaylist = await playlist.save()
        res.status(201).json(newPlaylist)
    } catch (err) {
        res.status(400).json({ message: err.message })
    }
})

但是,我遇到了这个错误

(node:23242) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'song' of undefined

我建议您也将第一部分包装在 try/catch 中。如果 req.body 不知何故没有被填充,或者如果 new Playlist 抛出任何类型的错误,因为这是一个异步函数,那将成为一个被拒绝的 Promise。这样更安全:

router.post('/', async (req, res) => {
    try {
        const playlist = new Playlist({
            song: req.body.song,
            artist: req.body.artist
        })
        const newPlaylist = await playlist.save()
        res.status(201).json(newPlaylist)
    } catch (err) {
        res.status(400).json({ message: err.message })
    }
})

如果您收到 "Cannot read property 'song' of undefined" 错误,这意味着请求 body 无法解析并保持 undefined。可能发送了错误的 content-type header 或者您没有正确设置 body 解析中间件。

您已经使用 try ... catch 处理了异常,这很棒。 尽管在此之外 try catch 可能是一个问题。 所以这里可能有两个错误

  1. req.body.songreq.body.artistPlaylist 不是有效的 class
  2. 在你的 catch 块上 res.status(400).json({ message: err.message }) 这可能是另一个问题。

如果您尝试捕获整个代码块并记录错误,那就太好了。

UnhandledPromiseRejectionWarning 发生是因为你没有捕捉到异常。