简体   繁体   中英

Why doesn't Node.js + express app crash on Error?

I am running Express 3.5.3 and node 0.10.29. I would like the app to crash and restart (using monit for this) when JSON is not parsed correctly. Unfortunately, the app does not crash when inside of an app.get handler. Here is my test code:

app.get("/api/pixel", function(req, res) {
  res.send(getPixel(), { 'Content-Type': 'image/gif' }, 200);
  JSON.parse("{123,adkljfl]")
});

I would expect the app to crash after trying to parse the bad JSON, but is does not. I would love to know why.

Are you using any error handling middleware? The default express scaffolding has these:

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

You can remove them if you want the app to crash, and you'd have to use something like forever or pm2 to make sure your app is restarted on crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM