Async/await helps write code that waits for tasks to finish. Handling errors properly keeps your program safe and clear.
0
0
Async/await error handling patterns in Node.js
Introduction
When calling a function that returns a promise and might fail
When you want to catch errors from asynchronous operations cleanly
When you want to avoid nested callbacks and make code easier to read
When you need to handle multiple async tasks and catch their errors
When debugging async code and want clear error messages
Syntax
Node.js
try { const result = await asyncFunction(); // use result } catch (error) { // handle error }
Use try to run code that might fail.
Use catch to handle any errors from the await call.
Examples
This example fetches data from an API and catches any errors during the fetch or JSON parsing.
Node.js
async function fetchData() { try { const data = await fetch('https://api.example.com/data'); const json = await data.json(); console.log(json); } catch (error) { console.error('Error fetching data:', error); } }
This example reads a file asynchronously and handles errors if the file is missing or unreadable.
Node.js
import fs from 'fs/promises'; async function readFile() { try { const content = await fs.readFile('file.txt', 'utf-8'); console.log(content); } catch (error) { console.error('Failed to read file:', error); } }
This example runs two async tasks in sequence and catches errors from either.
Node.js
async function processTasks() { try { const result1 = await task1(); const result2 = await task2(); console.log(result1, result2); } catch (error) { console.error('One of the tasks failed:', error); } }
Sample Program
This program tries to read a JSON config file asynchronously. If the file is missing or contains invalid JSON, it catches the error and prints a clear message.
Node.js
import fs from 'fs/promises'; async function readConfig() { try { const data = await fs.readFile('config.json', 'utf-8'); const config = JSON.parse(data); console.log('Config loaded:', config); } catch (error) { console.error('Error loading config:', error.message); } } readConfig();
OutputSuccess
Important Notes
Always use try/catch around await to avoid unhandled promise rejections.
You can also use Promise.allSettled() for multiple async calls to handle errors individually.
Logging error messages helps find problems quickly.
Summary
Use try/catch blocks to handle errors with async/await.
This makes async code easier to read and safer.
Always catch errors to prevent your program from crashing unexpectedly.