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')
.catch(console.log)
.then(() => fsp.readFile('anotherUnknownFile'))
.catch(console.log);
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'))
.catch(console.log);
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.
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
})
.catch(console.log);
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!'));
})
.catch(console.log);
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(/* ... */);
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
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.