0
0
Node.jsframework~5 mins

Promise catch for async errors in Node.js

Choose your learning style9 modes available
Introduction

Promises help handle tasks that take time, like loading data. Using catch lets you catch errors easily when something goes wrong.

When you want to handle errors from a task that runs later, like reading a file.
When calling an API and you want to catch if the request fails.
When working with timers or delays and need to handle possible errors.
When chaining multiple tasks and want to catch any error in the chain.
Syntax
Node.js
promiseFunction()
  .then(result => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

The catch method catches any error from the promise or previous then blocks.

It helps keep error handling separate and clear.

Examples
Fetch data and log it. If an error happens, log the error message.
Node.js
fetchData()
  .then(data => console.log(data))
  .catch(err => console.error('Error:', err));
Read a file asynchronously and print its content. If reading fails, show a message.
Node.js
readFileAsync('file.txt')
  .then(content => console.log(content))
  .catch(error => console.log('Failed to read file:', error));
Handle error directly if the async task fails, without a then block.
Node.js
someAsyncTask()
  .catch(err => console.log('Task failed:', err));
Sample Program

This program tries to read a file called example.txt. If it works, it prints the content. If the file is missing or unreadable, it catches the error and prints a friendly message.

Node.js
import { readFile } from 'node:fs/promises';

function readFileContent(path) {
  return readFile(path, 'utf8');
}

readFileContent('example.txt')
  .then(content => {
    console.log('File content:', content);
  })
  .catch(error => {
    console.log('Error reading file:', error.message);
  });
OutputSuccess
Important Notes

Always use catch to avoid unhandled promise errors that crash your program.

You can chain multiple then calls before a single catch to handle errors from any step.

Summary

Use catch to handle errors from promises cleanly.

catch helps keep your code safe and easy to read.

It works for any error in the promise chain.