express icon indicating copy to clipboard operation
express copied to clipboard

Why I can't send an error to front end through res.json()?

Open funkyLover opened this issue 9 years ago • 2 comments

I need to send an error object to front. just like

return res.json({ err: new Error('error') })
// also try res.send(JSON.stringify(new Error('error')))

but in browser

console.log(theErrorFromBackend) // {} ,get an empty object

node version 6.10.3 npm version 3.10.10 os macOS 10.12.4 express version ~4.15.2

to reproduce

$ express demo
$ cd demo && npm install # or yarn

and then modify demo/routes/users.js

router.get('/', function(req, res, next) {
  res.send(JSON.stringify(new Error('1231232')));
});

run npm start and visit localhost/3000/users in browser

funkyLover avatar Jun 08 '17 00:06 funkyLover

Sorry I post this issue, Finally I realize it is a feature not an issue😅 , I should handle the err in middleware, should call next(err) inside the api method.

funkyLover avatar Jun 08 '17 02:06 funkyLover

The explanation here might be helpful: https://stackoverflow.com/questions/44152189/error-in-promise-not-sending-any-error-in-response-object-in-nodejs-express-mong

ChinKX avatar Feb 22 '20 16:02 ChinKX