Async Error Handling in JavaScript
Handle async errors in JavaScript with try/catch and await, .catch on promises, Promise.all, Promise.allSettled and wrappers. Explanation and output.
1// Method 1: Async/await with try-catch2async function fetchData() {3 try {4 const response = await fetch('https://api.example.com/data');5 if (!response.ok) {6 throw new Error(`HTTP error! status: ${response.status}`);7 }8 const data = await response.json();9 return data;10 } catch (error) {11 console.error('Fetch error:', error.message);12 throw error;13 }14}1516fetchData().catch(error => {17 console.error('Unhandled:', error);18});1920// Method 2: Promise error handling21function promiseOperation() {22 return new Promise((resolve, reject) => {23 setTimeout(() => {24 if (Math.random() > 0.5) {25 reject(new Error('Random failure'));26 } else {27 resolve('Success');28 }29 }, 1000);30 });31}3233promiseOperation()34 .then(result => console.log('Result:', result))35 .catch(error => console.error('Error:', error.message));3637// Method 3: Multiple async operations38async function fetchMultiple() {39 try {40 const [data1, data2, data3] = await Promise.all([41 fetch('https://api.example.com/data1').then(r => r.json()),42 fetch('https://api.example.com/data2').then(r => r.json()),43 fetch('https://api.example.com/data3').then(r => r.json())44 ]);45 return [data1, data2, data3];46 } catch (error) {47 console.error('One or more requests failed:', error);48 throw error;49 }50}5152// Method 4: Promise.allSettled53async function fetchAllSettled() {54 const results = await Promise.allSettled([55 fetch('https://api.example.com/data1'),56 fetch('https://api.example.com/data2'),57 fetch('https://api.example.com/data3')58 ]);5960 results.forEach((result, index) => {61 if (result.status === 'fulfilled') {62 console.log(`Request ${index + 1} succeeded`);63 } else {64 console.error(`Request ${index + 1} failed:`, result.reason);65 }66 });67}6869// Method 5: Unhandled promise rejection (Node.js only)70if (typeof process !== 'undefined' && process.on) {71 process.on('unhandledRejection', (reason, promise) => {72 console.error('Unhandled rejection:', reason);73 });74}7576// Method 6: Async error wrapper77function asyncHandler(fn) {78 return (req, res, next) => {79 Promise.resolve(fn(req, res, next)).catch(next);80 };81}8283// Usage in Express84const asyncRoute = asyncHandler(async (req, res) => {85 const data = await fetchData();86 res.json(data);87});
Sample Output
Fetch error: Failed to fetch
The example URL is not a real API, so fetch fails. Node prints "fetch failed" instead.
Error: Random failure
This comes one second later. About half the time it is Result: Success instead.
In this one
- How to catch errors from await with try and catch
- Why fetch does not reject on a 404 reply
- The difference between Promise.all and Promise.allSettled
- How to watch for unhandled rejections
How it works
- 1
fetchData starts and fails to reach the server.
- 2
Its catch prints Fetch error and re-throws.
- 3
The caller .catch prints Unhandled.
- 4
After one second, promiseOperation prints success or failure.
- 5
fetchMultiple and fetchAllSettled are only defined.
Edge cases
Missing await
return fetch(...) without await lets errors skip the local catch.
Use return await inside try when you want to catch there.
HTTP errors look like success
A 404 reply still resolves the fetch promise.
Check response.ok and throw yourself.
Promise.all hides results
One failure throws away the other results.
Use Promise.allSettled when you need every result.
What's going on
Async code finishes later. A fetch request or a timer does not block the rest of the script. Because of that, a normal try around the call cannot catch errors that happen later. JavaScript gives you two tools: await inside try, and .catch on a promise.
A promise is an object that will later hold a result or an error. "Reject" means the promise failed.
Method 1 awaits fetch inside try. await pauses the async function until the promise settles. If fetch fails, the catch runs. The code also checks response.ok, because fetch does not reject for 404 or 500 replies. It throws its own error for those. Then it re-throws, so the caller's .catch prints a second line.
Method 2 uses .then for success and .catch for failure. The timer waits one second, and Math.random picks the result, so you may see Result: Success or Error: Random failure.
Method 3 uses Promise.all. It rejects as soon as any one promise fails. Method 4 uses Promise.allSettled, which waits for all of them and reports each one as fulfilled or rejected. Both are defined but not called here, so they print nothing.
Method 5 listens for unhandled rejections in Node.js. The code checks that process exists, so it does not crash in a browser. Method 6 is a wrapper for Express routes that sends any async error to next, the error handler.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does fetch do for a 404 reply?
Pick an answer to check it.
Question 2
Which one waits for every promise even if some fail?
Pick an answer to check it.
Questions people ask
Can a normal try catch a promise error?
Only if you await the promise inside the try.
What is an unhandled rejection?
A rejected promise with no .catch or try around its await.
Is .catch or try/catch better?
They do the same job. Use the one that matches your code style.