6

I am learning error/exception handling and I do not understand how process.on('uncaughtException', ...) is used. Can you use it the same way as try and catch, or does it only handle exceptions?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
CodeHip
  • 367
  • 5
  • 18

1 Answers1

0

As said in the Process Documentation provide information and control over, the current (node) process.

I'd use it a lot on backend development with node/express, a simple example? logging the errors of my application

 // ERROR LOG MANAGEMENT
// =====================================================================
let errorLogStream = fs.createWriteStream(__dirname + '/logs/error.log', {
  flags: 'a'
})

// ERROR HANDLING
// =====================================================================
process.on('uncaughtException', (err, next) => {
  var date = new Date()
  console.error(`+++++++ ${date} error found, logging event +++++++`)
  console.error(err.stack)
  errorLogStream.write(`Date: ${date}. Err: ${err.stack}`)
  return
})

I think the main difference its said by the event name itself, if you are executing some task and have an error, handle it, why do you would throw it to catch it there? i mainly use it for non-related issues with my logic

DobleL
  • 3,808
  • 14
  • 20