Register to get access to free programming courses with interactive exercises

Error Handling in Promises JS: Asynchronous programming

Errors inside promises are very easy to handle. To catch them, it's enough to call the catch method and pass it the callback that takes the error itself as input:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile');
promise.catch((e) => console.log('error!!!', e));
// => error!!! { [Error: ENOENT: no such file or directory, open 'unknownfile']
// errno: -2, code: 'ENOENT', syscall: 'open', path: 'unknownfile' }

In turn, catch returns a promise, which allows the code to handle the error and continue the chain. It's quite normal to write code that looks like a chain where then and catch alternate:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .catch(console.log)
  .then(() => fsp.readFile('anotherUnknownFile'))
  .catch(console.log);

In most situations, it doesn't matter in which operation the error occurred. An error will stop the current execution and go to the error handling block. This is exactly how the try/catch code works; and the same behavior is emulated by promises. When an error occurs, it is passed up the chain to the first catch encountered, and any then encountered along the way is ignored. So, we can return to the code above and simplify it like this:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .then(() => fsp.readFile('anotherUnknownFile'))
  .catch(console.log);

Semantically, these versions of the code aren't equivalent. In the first version, the second reading operation starts regardless of how the previous one ended. In the latter case, if there's an error during the first reading, the second one won't happen.

Processing errors in promises

Sometimes you need to generate the error yourself. The easiest way is to throw an exception. You also have to get used to this. You can't use the try/catch because it's useless, but you can throw exceptions. Promise itself converts them as needed and sends them up the chain looking for a catch call:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .then((data) => {
    // doing something
    throw new Error('boom!');
  })
  .then(() => {
    // It won't be called because of the exception in the previous step
  })
  .catch(console.log);

Another way is to return the result of a call to the Promise.reject function, to which we pass the error:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .then((data) => {
    // Doing something
    return Promise.reject(new Error('boom!'));
  })
  .catch(console.log);

In addition to the purely technical aspects of error handling, there are also architectural and organizational aspects. If you have to implement asynchronous functions that other people will use, never suppress errors:

import fsp from 'fs/promises';

const readFileEasily = (filepath) => fsp.readFile(filepath).catch(console.log);

By intercepting an error, you leave no chance for the code calling the asynchronous function to know about it. The code that uses this function won't be able to react to any situation that occurs because of an error. If you still need to handle the error, do so, but don't forget to regenerate:

import fsp from 'fs/promises';

const readFileEasily = (filepath) => fsp.readFile(filepath)
  .catch((e) => {
    console.log(e); // You can't do that in libraries, only in your own code
    throw e;
  });

// The calling code can now handle the error:

readFileEasily('path/to/file').catch(/* ... */);

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.