Async Error Handling in JavaScript

Handle errors in async operations

IntermediateError HandlingExample 4 of 10
async-error-handling.js
1// Method 1: Async/await with try-catch
2async 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}
15
16fetchData().catch(error => {
17 console.error('Unhandled:', error);
18});
19
20// Method 2: Promise error handling
21function 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}
32
33promiseOperation()
34 .then(result => console.log('Result:', result))
35 .catch(error => console.error('Error:', error.message));
36
37// Method 3: Multiple async operations
38async 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}
51
52// Method 4: Promise.allSettled
53async 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 ]);
59
60 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}
68
69// Method 5: Unhandled promise rejection
70process.on('unhandledRejection', (reason, promise) => {
71 console.error('Unhandled rejection:', reason);
72});
73
74// Method 6: Async error wrapper
75function asyncHandler(fn) {
76 return (req, res, next) => {
77 Promise.resolve(fn(req, res, next)).catch(next);
78 };
79}
80
81// Usage in Express
82const asyncRoute = asyncHandler(async (req, res) => {
83 const data = await fetchData();
84 res.json(data);
85});

Output

Fetch error: Failed to fetch
Error: Random failure
One or more requests failed: Error
Request 1 succeeded
Request 2 failed: Error
Request 3 succeeded

What's going on

Async error handling requires special care.

Async/Await

Use try-catch
Handle in async functions
Re-throw if needed

Promises

.catch() handler
Chain error handling
Handle rejections

Promise.all

Fails fast
First error stops all
Use try-catch

Promise.allSettled

All complete
Check status
Handle individually

Unhandled Rejections

Global handler
Log errors
Prevent crashes

Best Practices

Always handle errors
Use asyncHandler wrapper
Log properly
Don't ignore rejections