Node.js Error Handling Tutorial

In this tutorial, you will learn how to manage errors in Node.js Applications.

Introduction to Error Handling

  1. Error handling is the process of managing and responding to errors or exceptions in your code.
  2. In Node.js, errors can occur due to various reasons, such as incorrect input, network issues, or file system problems.

Types of Errors

    In Node.js, errors can be categorized into two main types:

  1. Synchronous Errors: These occur during the execution of synchronous code and can be caught using try...catch.
  2. Asynchronous Errors: These occur in asynchronous code, such as callbacks and Promises.

The try...catch Statement:

  1. The try...catch statement is used to catch and handle synchronous errors.
  2. It allows you to define a block of code to try, and if an error occurs, you can catch and handle it.
try {
    // program that might throw an error
  } catch (error) {
    // handle the error
    console.error('An error occurred:', error.message);
  }
  

Throwing Custom Errors

  1. You can create and throw custom errors using the throw statement.
try {
    throw new Error('Custom error message');
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
  

Error Events

  1. In Node.js, some objects emit 'error' events when something goes wrong.
  2. You can listen for these events to handle errors.
const fs = require('fs');
const fileStream = fs.createReadStream('nonexistent-file.txt');

fileStream.on('error', (error) => {
    console.error('An error occurred:', error.message);
});
    

Error-First Callbacks

  1. Node.js commonly uses the error-first callback pattern, where callbacks receive an error as the first argument.
function readDataFromFile(callback) {
fs.readFile('file.txt', 'utf-8', (err, data) => {
    if (err) {
    callback(err);
    return;
    }
    callback(null, data);
});
}
  

Handling Errors in Asynchronous Code

  1. In asynchronous code, errors can be handled by checking for errors in the callback or using try...catch around async/await code.
async function fetchData() {
    try {
      const data = await fetchDataFromServer();
      console.log('Data:', data);
    } catch (error) {
      console.error('Error:', error.message);
    }
  }
  

Promises and Async/Await for Error Handling

  1. Promises in Node.js provide a structured way to handle asynchronous operations and errors.
  2. You can use catch with Promises or use async/await to handle Promise rejections.
fetchDataFromServer()
    .then((data) => {
      console.log('Data:', data);
    })
    .catch((error) => {
      console.error('Error:', error.message);
    });