Abazhenov / express-async-handler

Async Error Handling Middleware for Express
572 stars 39 forks source link

How to get the result response as JSON format #44

Open sesuchristo opened 3 years ago

sesuchristo commented 3 years ago

I need the error handler return response as json format. But I couldn't find any option for format change

heidemn commented 3 years ago

This library doesn't implement an error handler. It only makes sure that async errors are passed to Express, so the Express default error handler or your custom error handler can handle them.

You would have to do something like this (not tested): http://expressjs.com/en/guide/error-handling.html#writing-error-handlers

express.get('/example-error', asyncHandler(async (req, res, next) => {
        const err = new Error("Oh noes!");
        err.more_info = 42;
    await Promise.reject(err);
    res.send("unreachable");
}))

// Error handler (identified by having four arguments)
app.use(function (err, req, res, next) {
  console.error(err.stack);
  errJson = Object.assign({}, err); // create POJO
  // Assign properties from prototype which would be missing otherwise.
  errJson.constructor_name = err.constructor.name;
  errJson.message = err.message;
  if (process.env.NODE_ENV !== 'production') { errJson.stack = err.stack; }
  res.status(500).send(errJson);
})