0
votes

I'm trying to handle errors using express middleware, with these lines I have the following errors

user.js controller

app.post('/create', async (req, res, next) => {
  const data = await User.create(req.body)
    .catch((err) => next(err));
  res.status(201).json({ ok: true, ...data });
});

user.js model

UserSchema.statics.create = async function createUser(data) {
  delete data.role;
  const user = await new this(data).save();
  return { token: user.newToken(), user };
};

app.js

app.use((err, req, res, next) => {
  res.status(err.code || 400);
  res.json({ ok: false, err: err.message });
});

Errors

(node:3304) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client ...

(node:3304) 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: 9)

(node:3304) [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.

After to proof with try/catch in the user.js controller i don't have any error, but in the express documentation use try/catch is not recommended.

app.post('/create', async (req, res, next) => {
  try {
    const data = await User.create(req.body)
    res.status(201).json({ ok: true, ...data });
  } catch (err) {
    next(err);
  }
});

Any ideas?

1

1 Answers

0
votes

You either use await or then/catch:

app.post('/create', async (req, res, next) => {
  User.create(req.body)
    .then(data => {
       res.status(201).json({ ok: true, ...data });
     })
    .catch((err) => next(err));
});