0
0
Node.jsframework~5 mins

Error events and handling in Node.js

Choose your learning style9 modes available
Introduction

Error events and handling help your program catch problems and respond without crashing. It keeps your app running smoothly and lets you fix or report errors.

When reading a file that might not exist
When making a network request that could fail
When working with streams that might emit errors
When handling user input that could be invalid
When connecting to a database that might be unreachable
Syntax
Node.js
emitter.on('error', (err) => {
  // handle the error here
});
Use the 'error' event on objects that emit events, like streams or servers.
Always handle 'error' events to avoid your program crashing.
Examples
This listens for errors when reading a file and logs a message if an error happens.
Node.js
const fs = require('fs');
const stream = fs.createReadStream('file.txt');

stream.on('error', (err) => {
  console.error('Error reading file:', err.message);
});
This handles errors on a network server, like if the port is already in use.
Node.js
const net = require('net');
const server = net.createServer();

server.on('error', (err) => {
  console.error('Server error:', err.message);
});
Sample Program

This program tries to read a file that does not exist. Instead of crashing, it catches the error and prints a message.

Node.js
import { createReadStream } from 'node:fs';

const stream = createReadStream('missing.txt');

stream.on('error', (err) => {
  console.log(`Caught error: ${err.message}`);
});
OutputSuccess
Important Notes

Always add an 'error' event listener on streams and servers to prevent crashes.

Errors provide useful info in the error object, like message and code.

Use try-catch blocks for synchronous code, but use 'error' events for asynchronous event emitters.

Summary

Error events let you catch problems in asynchronous code.

Always handle 'error' events on event emitters like streams and servers.

Handling errors keeps your app stable and user-friendly.