Zach Zach - 11 months ago 61
Javascript Question

uncaughtException then appendFile on error will this cause problems? NodeJs

I'm curious about if since process.exit(1) is in the callback of a async
operation, the appendFile, if where the original error happened will continue running and be in an unstable state. I tried to put the process.exit(1) inline with the fs but it wouldn't write.

better ways to create a error logged that will log on any error would be appreciated. .

const fs = require('fs');

process.on('uncaughtException', e1 => {
fs.appendFile('./logs/error.log', e1.stack, e2 => {
//if (e1 || e2) console.log(e1,e2);



Answer Source

As is, looks like your program will exit with an error code to the console every time it finishes with fs.appendFile. process.exit should kill anything else running once it hits that.

I'd probably do something like this:

const fs = require('fs');

process.on('uncaughtException', function (err) {
  fs.appendFile('./logs/error.log', err.stack, (fserr) => {
    if (err) console.log('FS ERROR', fserr); //now includes the fs error in log
    console.log(err); //maybe include error from uncaughtException?
    process.exit(1); //exit with error code