Efaz
Efaz

Reputation: 304

Handling promise and async await function

I have this function in node and 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 })
    }
})

However, I am getting this error

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

Upvotes: 1

Views: 119

Answers (2)

Tian Ming
Tian Ming

Reputation: 151

You have handled the exception using try ... catch and this is great. Although outside of this try catch can be an issue. So there might to be two errors here

  1. Either req.body.song or req.body.artist OR Playlist is not a valid class
  2. On your catch block res.status(400).json({ message: err.message }) this could be another issue.

It would be great if you try and catch entire code block and log the err and it would be clear.

UnhandledPromiseRejectionWarning is happened because you didn't catch the exception.

Upvotes: 0

Jacob
Jacob

Reputation: 78850

I'd recommend you also wrap that first part in a try/catch. If req.body somehow doesn't get populated, or if new Playlist throws any sort of error, since this is an async function, that'll become a rejected Promise. This is safer:

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 })
    }
})

If you're getting a "Cannot read property 'song' of undefined" error, that means that the request body could not be parsed and remains undefined. Maybe the wrong content-type header was sent or you don't have a body parsing middleware set up correctly.

Upvotes: 1

Related Questions