Promise.prototype.catch
Handles a promise's error.
Available since: ES2015
Syntax
promise.catch(onRejected)Parameters
| Parameter | Type | Description |
|---|---|---|
| onRejected | Function | A function that receives the error. |
Return value
PromiseA new promise — after the error is handled the chain continues.
Examples
Catching an error:
Promise.reject(new Error('Network error'))
.catch((error) => console.log('Caught:', error.message));Output:
Caught: Network errorOne catch for the whole chain:
Promise.resolve('{bad json')
.then((text) => JSON.parse(text))
.then((data) => console.log('not printed', data))
.catch((error) => console.log(error.name));Output:
SyntaxErrorNotes
An error in any then() skips the remaining then() calls and goes to the nearest catch(). A rejected promise without catch() shows an Uncaught (in promise) warning in the console.
See also
- Promise.prototype.then — Says what to do with a promise's result.
- Promise.prototype.finally — Runs an action after a promise — on success and on failure.
- try...catch — Catches errors so the program does not stop.
In the tutorial
- Promises — Promises in JavaScript: promise states, then, catch, finally, creating a promise with new Promise, and chains.