Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created December 6, 2017 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/84d6e55ad577f9dd5ab3d1e401a73938 to your computer and use it in GitHub Desktop.
Save akirattii/84d6e55ad577f9dd5ab3d1e401a73938 to your computer and use it in GitHub Desktop.
[nodejs] How to catch unknown exception and shutdown the express instance on low level layer
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function(req, res) {
res.send("hello");
// Notice: Make any uncaughtException happend on purpose
fs.readFile('no_such_file.txt', function(err, data) {
if (err) throw err;
console.log(data);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
//
// write an uncaught error log just before the system is shut down:
//
process.on('uncaughtException', (err) => {
console.error("uncaughtException: err:", err, "\nerr.stack:", err.stack);
// Here, app instance must be killed for system consistency.
// if use any process managemer such as Forever, app is restarted perfectly
process.abort();
});
/*
# start server:
$ node server.js
or
$ forever start server.js
### log:
Example app listening on port 3000!
# Open http://localhost:3000 on browser:
### log:
uncaughtException: err: { Error: ENOENT: no such file or directory, open 'no_such_file.txt'
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'no_such_file.txt' }
err.stack: Error: ENOENT: no such file or directory, open 'no_such_file.txt'
1: node::Abort() [node]
2: 0x1218409 [node]
3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [node]
4: 0xb8ee3c [node]
5: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [node]
6: 0x89d6698463d
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment