express-async-handler icon indicating copy to clipboard operation
express-async-handler copied to clipboard

How to get the result response as JSON format

Open sesuchristo opened this issue 4 years ago • 1 comments

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

sesuchristo avatar May 22 '21 12:05 sesuchristo

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

heidemn avatar Aug 18 '21 20:08 heidemn