
How can I handle errors in an async function using try/catch with promises?
Asked on Oct 10, 2025
Answer
In JavaScript, you can handle errors in an async function by using a try/catch block. This allows you to catch errors from promises that are awaited within the function.
<!-- BEGIN COPY / PASTE -->
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw the error if needed
}
}
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "fetchData" function is an async function that uses "await" to handle the promise returned by "fetch".
- The "try" block is used to attempt to fetch data and parse it as JSON.
- If the "fetch" fails or the response is not "ok", an error is thrown.
- The "catch" block logs the error and can re-throw it if you want to handle it further up the call stack.
Recommended Links:
← Back to All Questions