MyInternships.in

Node.js Basics

Node.js Error Handling

Node errors arrive in three ways: thrown exceptions in synchronous code, rejected promises in async code, and error events on streams and emitters. Each needs a different mechanism, and missing any one crashes the process.


What is Error Handling in Node.js?

Node errors arrive in three ways: thrown exceptions in synchronous code, rejected promises in async code, and error events on streams and emitters. Each needs a different mechanism, and missing any one crashes the process.

Error Handling example

All three, handled
JavaScript
// synchronous
try {
  JSON.parse(raw);
} catch (err) {
  console.error('Invalid JSON:', err.message);
}

// async
try {
  const data = await readFile('config.json', 'utf8');
} catch (err) {
  if (err.code === 'ENOENT') console.error('Config file missing');
  else throw err;
}

// emitter — an unhandled 'error' event crashes the process
stream.on('error', err => console.error('Stream failed:', err));

Custom errors carry useful context

JavaScript
class AppError extends Error {
  constructor(message, statusCode = 500, code = 'INTERNAL') {
    super(message);
    this.name = 'AppError';
    this.statusCode = statusCode;
    this.code = code;
    Error.captureStackTrace(this, this.constructor);
  }
}

throw new AppError('Job not found', 404, 'JOB_NOT_FOUND');

Key points to remember

  • Check err.code rather than parsing err.message — messages change between versions.
  • Handle process-level unhandledRejection and uncaughtException for logging, then exit.
  • Never swallow an error silently; log it with enough context to act on.

Error codes you will meet constantly

CodeMeaning
ENOENTfile or directory does not exist
EACCESpermission denied
EADDRINUSEthe port is already in use
ECONNREFUSEDnothing is listening at the target address
ETIMEDOUTthe operation took too long
ERR_MODULE_NOT_FOUNDan ES module import path is wrong

Common mistakes with Error Handling

  • An unhandled promise rejection, which terminates the process in modern Node.
  • try/catch around a callback-style API, which never catches anything.

Node.js Error Handling— Interview Questions & FAQs

Why does my Node app crash with EADDRINUSE?+

Another process is already listening on that port — often a previous run that did not exit. Find it with lsof -i :3000 and stop it, or use a different port.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships