Register to get access to free programming courses with interactive exercises

Error Handling in Promises JS: Asynchronous programming

Errors within promises are extremely easy to handle. For the purposes of intercepting them, it's enough to call the catch method and pass to it the callback that takes the error itself as an 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' }

catch, in turn, returns a promise, which allows the code to recover from errors and continue the chain. It's quite normal to write code that looks like a chain, in which then and catch alternate:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .then(() => fsp.readFile('anotherUnknownFile'))

In most situations, it doesn't matter which operation the error occurred at. Any failure must interrupt the current execution and go to the error handling block. This is exactly how try/catch, code works, and the same behavior is emulated by promise. The point is that if an error occurs, it is passed up the chain to the first catch, encountered, and all then encountered along the way are ignored. Therefore, the code above can be simplified like this:

import fsp from 'fs/promises';

const promise = fsp.readFile('unknownfile')
  .then(() => fsp.readFile('anotherUnknownFile'))

In terms of semantics, these versions of the code aren't equivalent. In the first case, the second reading operation will begin, regardless of how the previous one ended. In the latter, if there's a failure during the first reading operation, the second won't be executed.

Processing errors in promises

Sometimes you have to generate the error yourself. The easiest way to do this is to throw an exception. You have to get used to it, too. try/catch can't be used (because it is useless), but exceptions can be thrown. Promise itself converts them as needed and sends them along the chain in search of a catch call:

import fsp from 'fs/promises';

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

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

import fsp from 'fs/promises';

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

In addition to purely technical aspects of error handling, there are 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 occurring because of an error. If you still need to process the error, do it, but don't forget to generate it again:

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(/* ... */);

Hexlet Experts

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

The Hexlet support team or other students will answer you.

About Hexlet learning process

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
hours of theory

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:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Development of front-end components for web applications
start anytime 10 months

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.