Error handling with async/await helps you catch problems in your code when waiting for tasks to finish. It keeps your program from crashing and lets you respond nicely to errors.
0
0
Error handling in async/await in Node.js
Introduction
When calling a function that returns a promise and might fail
When you want to handle errors clearly without nested callbacks
When you want to keep your code easy to read and understand
When working with network requests that can fail
When reading or writing files asynchronously
Syntax
Node.js
async function example() { try { const result = await someAsyncTask(); // use result } catch (error) { // handle error here } }
Use try to run code that might fail.
Use catch to handle any errors that happen inside try.
Examples
This example fetches data from a website and catches errors if the fetch fails.
Node.js
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Failed to fetch 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('Error reading file:', error); } }
Sample Program
This program tries to read a JSON config file. If the file is missing or has bad JSON, it catches the error and prints a friendly 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('Could not load config:', error.message); } } readConfig();
OutputSuccess
Important Notes
Always use try/catch around await to catch errors.
You can also handle errors by returning promises and using .catch(), but try/catch is cleaner with async/await.
Remember to keep error messages clear to help debugging.
Summary
Use try/catch blocks to handle errors in async functions.
Put await calls inside try to catch failures.
Handling errors prevents crashes and helps your app respond smoothly.