2016년 8월 12일 금요일

애플리케이션 종료 막기

Event: 'uncaughtException'

The 'uncaughtException' event is emitted when an exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting. Adding a handler for the'uncaughtException' event overrides this default behavior.
For example:
process.on('uncaughtException', (err) => {
  console.log(`Caught exception: ${err}`);
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

Warning: Using 'uncaughtException' correctly

Note that 'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to On Error Resume Next. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.
Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non zero exit code and the stack trace will be printed. This is to avoid infinite recursion.
Attempting to resume normally after an uncaught exception can be similar to pulling out of the power cord when upgrading a computer -- nine out of ten times nothing happens - but the 10th time, the system becomes corrupted.
The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after 'uncaughtException'.

아무런 대응없이 허무하게 프로세스가 강제종료 되는 현상을 막을 수 있다.






커스텀 콘솔

Class: Console

The Console class can be used to create a simple logger with configurable output streams and can be accessed using either require('console').Console or console.Console:
const Console = require('console').Console;
const Console = console.Console;

new Console(stdout[, stderr])

Creates a new Console by passing one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr isn't passed, warning and error output will be sent to stdout.
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
var count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
The global console is a special Console whose output is sent to process.stdout and process.stderr. It is equivalent to calling:
new Console(process.stdout, process.stderr);