0
votes

I have a Post that uses Busboy. the events fire correct and the data returned is proper, but the catch generates a UnhandledPromiseRejectionWarning.

This is the code:

route.post("/", (req, res) => {
  const busboy = new Busboy({ headers: req.headers })
  if (req["currentUser"] === null) {
    res.sendStatus(401).send({ "error": "Unauthorized" }).end()
  }
  const data = {}
  busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
    data[fieldname] = val
  });
  busboy.on('finish', () => {
    if (data['name'] === undefined || data['price'] === undefined || data["description"] === undefined
      || data["vendor"] === undefined || data['category'] === undefined || data['image'] === undefined) {
      res.sendStatus(400).send({ "error": "Bad Request" }).end()
    }
    const response = db.collection("products")
      .doc(uuidv4())
      .set(data)

    response.then((response) => {
      res.sendStatus(200).send(data).end()
    }).catch(err => {
      res.sendStatus(400).send(err).end()
    })

  });
  busboy.end(req.rawBody)
})

route.get("/", async (req, res) => {
  res.set('Content-Type', 'application/json');

  if (req["currentUser"] === null) {
    return res.status(401).send({ "error": "Unauthorized" });
  }
  if (req.query.id === undefined) {
    res.sendStatus(400).send({ "error": "Bad Request" });
  }
  const productData = db.collection("products")
    .doc(req.query.id).get()

  if (!productData.exists) {
    res.send(404).send({ "error": "No Product Found" })
  } else {
    res.send(200).send(JSON.stringify(productData.data()))
  }
})

and this is the error.

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(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:17812) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1

1 Answers

1
votes

The error means that either a Promise is missing a catch-Block or that you have an async function throwing an error. Looking at your code I would guess that somewhere in the route route.get("/", async (req, res) => { an error is thrown which can't be handled.

Try wrapping everything inside the bottom route in a try-Block and add a catch-Block that e.g prints the error. Your error should be fixed then.