1

How to handle errors in http requests?

Here the full error is returned to the client.. How to write the error to the log and return Fatal error to the client?

Express v4.4.4

var express = require('express'),
    app = express(),
    domain = require('domain'),
    port = 3000;

app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send('Fatal error!', 500);
});

app.get('/', function(req, res){
    var d = domain.create();
    d.on('error', function(err){
        console.error('Error', err);

        res.send('Fatal error!', 500);
    });
    d.add(req);
    d.add(res);
    d.run(function(){
        //  a is undefined
        a.ddd();

        res.send('Success!');
    });
})
.listen(port, function(){
    console.log('Express server listening on port '+port);
});
4
  • expressjs.com/guide.html#error-handling Commented Jun 23, 2014 at 17:32
  • have updated my question.. still sending the error stack to the client Commented Jun 23, 2014 at 17:39
  • Buddy - 'app.use' is an example. Commented Jun 23, 2014 at 17:43
  • check the link for better understanding Commented Jun 23, 2014 at 17:44

2 Answers 2

3

Your .use for the error handler needs to be at the bottom, after the routes/handlers/middlewhare which may cause the errors. Then from your other places, call next(error) instead of returning an error message directly

// this comes first
app.get('/', function(req, res, next){ // note the addition of next
    var d = domain.create();
    d.on('error', function(err){
        next(err); // pass the error on to the next middleware
    });
    // ... 
});

// this comes last
app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send('Fatal error!', 500);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4, that is the signature (err, req, res, next):

Express Error Handling

eg code:

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.