JavaScript Reference ยท Promises and Async
Promise.prototype.catch()
Reference for Promise.prototype.catch(): handle rejections and errors in promise chains, recover with a fallback value, and avoid unhandled rejections.
The catch() method registers a handler that runs when a promise is rejected, or when an earlier step in the chain throws. It returns a new promise, so the chain can continue after the error has been dealt with.
Calling catch(onRejected) is the same as calling then(undefined, onRejected). It is usually placed at the end of a chain, where it catches a failure from any step before it.
loadUser() .then(showUser) .catch((error) => console.log("failed:", error.message));
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
promise.catch(onRejected)
| Name | Description |
|---|---|
onRejected |
Called with the rejection reason. The reason can be any value, but is usually an Error. |
Return value: a new promise. It fulfills with the handler's return value, and rejects if the handler throws or returns a rejected promise. If the original promise fulfills, catch() is skipped and its value passes through.
Exceptions: none directly; errors thrown in onRejected reject the returned promise.
Usage notes
- Place it last. A
catch()at the end handles errors from every earlierthen(), including errors thrown by your own code in those handlers. - Returning recovers, throwing propagates. Return a value to resume normal flow; rethrow what you cannot handle.
- An empty
catch(() => {})hides bugs. Log or surface errors, at least in development. - Check the type of error. Use
instanceoforerror.nameto separate expected failures from programming mistakes. - A missing handler is dangerous. A rejection nobody handles causes an
unhandledrejectionevent in browsers and may terminate Node.js. fetch()only rejects on network failure. An HTTP 404 still fulfills; checkresponse.okand throw yourself.- With
await, usetry...catchinstead; it works the same way.
Browser support
Supported in every current browser and Node.js.