I am beginning to work with Express JS and have run into an issue. I can't seem to figure out the proper way to handle errors.
For example, I have a web services API that serves an object called "event". I'd like to return a simple string of "cannot find event" when a user submits an event id that isn't found. Here is how I'm currently structuring my code:
app.get('/event/:id', function(req, res, next) { if (req.params.id != 1) { next(new Error('cannot find event ' + req.params.id)); } req.send('event found!'); });
When I submit an id other than 1, Node crashes with the following output:
http.js:527 throw new Error("Can't set headers after they are sent."); ^ Error: Can't set headers after they are sent. at ServerResponse.<anonymous> (http.js:527:11) at ServerResponse.setHeader (/usr/local/kayak/node_modules/express/node_modules/connect/lib/patch.js:62:20) at /usr/local/kayak/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js:72:19 at [object Object].<anonymous> (fs.js:107:5) at [object Object].emit (events.js:61:17) at afterRead (fs.js:878:12) at wrapper (fs.js:245:17)
From what I can tell by using the node.js debugger, execution of the block of code continues after next()
is called, meaning that req.send('event found!')
tries to run. I don't want this to happen.
The only workaround that I've found is to simply throw a new Error()
instead of "next-ing" it, but this results in a default Express HTML error page being generated. I'd like a little more control than that.
I have taken the time to read over the error handling section of the Express documentation, but I couldn't make sense of it.
You'll want to check out Express Error Handling. From there:
app.param('userId', function(req, res, next, id) { User.get(id, function(err, user) { if (err) return next(err); if (!user) return next(new Error('failed to find user')); req.user = user; next(); }); });
The sweetspot that you are missing is the return
next(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With