'How to solve "Unhandled promise rejection" error?

I was trying to reuse the existing and working function in my azure timer trigger function. But I encountered an error below.

(node:66694) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch().

I already tried to wrap try-catch the setTimeout but still, the same error occurred.


here is my code:

export const request = async (
  reuqestOptions: Options,
  waitTime?: number
): Promise<Response> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // ... more code here
      
      const req = https.request(options, (res) => {
        // ... more code here

        res.on('end', async () => {
          // ... more code here

          resolve({
            body: result,
            statusCode: res.statusCode,
            headers: res.headers,
          })
        })
      })

      req.on('error', (e) => {
        console.log(e.message)
      })

      req.end()
    }, 3000 || 0)
  })
}

here is how I call request:

export const requestToken = async (
  usernmae: string,
  password: string
): Promise<any> => {
  try {
    const response = await request({
      method: 'POST',
      // ...more code here
    })

    if (response.statusCode !== 200) {
      throw new Error(JSON.stringify(response.body))
    }

    return response
  } catch (error) {
    throw new Error('request token is invalid')
  }
}


Solution 1:[1]

So you have two places where you need to catch the error, or say, put a try block. First one would be the place where you make the http request. The other one would be the place where you actually call this function (which returns the promise).

wrapping the setTimeout in a try catch block will have no consequence as by the time the callback is fired, the try block would have ended.

For first case, you are registering an "error" callback, so thats all good. You just need to handle the second case (Promise).

export const request = async (
  reuqestOptions: Options,
  waitTime?: number
): Promise<Response> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // ... more code here
      
      const req = https.request(options, (res) => {
        // ... more code here

        res.on('end', async () => {
          // ... more code here

          resolve({
            body: result,
            statusCode: res.statusCode,
            headers: res.headers,
          })
        })
      })

      req.on('error', (e) => {
        console.log(e.message)
      })

      req.end()
    }, 3000 || 0)
  }).catch(err){
//...handle your error here
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 D.B.K