01 / 21
!

Error Handling in
Async Code

Master try/catch with await to write robust asynchronous JavaScript that handles failures gracefully and never silently swallows errors.

JavaScript

What is Asynchronous Code?

JavaScript is single-threaded: it executes one line at a time. But some operations: fetching data from servers, reading files, or waiting for timers: take time. Instead of blocking the entire program, JavaScript lets these operations run in the background and notifies you when they finish.

Synchronous
Each line waits for the previous line to complete before running
Asynchronous
Long-running tasks start now, and your code handles the result later

Promises: The Foundation

A Promise is an object that represents a value that may not exist yet. It has three states:

Pending Fulfilled (has a value) Rejected (has an error) .then() handle value .catch() handle error A promise either resolves with a value or rejects with an error

async/await: Cleaner Syntax

The async/await syntax lets you write asynchronous code that reads like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a promise settles.

async function fetchUser() { const response = await fetch('/api/user'); const data = await response.json(); return data; }

Why Errors Happen in Async Code

Async operations interact with the outside world: networks, servers, filesystems. Any of these can fail unpredictably. Your code must anticipate and handle these failures.

Network Failures
Server is down, connection times out, DNS fails
Bad Responses
Server returns 404 or 500, malformed JSON data
Logic Errors
Accessing properties on null, type mismatches

The Core Pattern: try/catch with await

Wrap your await expressions inside a try block. If the promise rejects, execution jumps to the catch block: just like synchronous error handling.

try { } await someAsync() process result runs normally success Continue execution skip catch block error thrown catch (err) { } handle the error log, retry, or notify finally { } always runs (optional)

The Syntax in Full

async function loadData() { try { const response = await fetch('/api/data'); const json = await response.json(); console.log(json); } catch (error) { console.error('Failed to load:', error.message); } finally { console.log('Request complete.'); } }

.then/.catch vs try/catch

Both approaches handle async errors, but try/catch with await produces cleaner, more readable code: especially when you have multiple sequential async operations.

.then/.catch try/catch + await
Readability Callback chains can nest deeply Reads top-to-bottom like sync code
Error scope Each .catch() handles its own chain One catch block covers all awaits
Debugging Stack traces can be fragmented Clearer stack traces
Control flow Harder to use if/else, loops Works naturally with all control flow

How to Apply the Pattern

1
Mark the function as async. Add the async keyword before the function declaration.
2
Wrap await calls in try { }. Place all lines that use await inside the try block.
3
Add catch (error) { }. Log the error, show a user message, or retry the operation.
4
Use finally { } for cleanup. Hide loading spinners, close connections, or reset state.
5
Be specific about what you catch. Check error types or status codes to handle different failures differently.

Example 1: Basic Fetch

async function getUser(id) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) { throw new Error(`HTTP ${res.status}`); } const user = await res.json(); return user; } catch (err) { console.error('Failed:', err.message); return null; } }

Example 2: Multiple Awaits

async function loadDashboard() { try { const user = await fetchUser(); // await 1 const posts = await fetchPosts(user.id); // await 2 const stats = await fetchStats(user.id); // await 3 renderDashboard(user, posts, stats); } catch (err) { showErrorBanner(err.message); } finally { hideLoadingSpinner(); } }

Example 3: Parallel with Promise.all

async function loadAll() { try { const [users, products] = await Promise.all([ fetch('/api/users').then(r => r.json()), fetch('/api/products').then(r => r.json()) ]); render(users, products); } catch (err) { // If ANY promise rejects, we land here console.error('One request failed:', err); } }

Granular Error Handling

Sometimes you want to handle errors from each await differently instead of one blanket catch. You can use nested try/catch or check the error type inside catch.

async function processOrder(orderId) { try { const order = await fetchOrder(orderId); try { await chargePayment(order); } catch (payErr) { await refund(order); // specific recovery throw payErr; // re-throw to outer catch } await sendConfirmation(order); } catch (err) { logError(err); } }

The Error Object

When catch receives an error, it is an Error object with useful properties for debugging.

error.message
A human-readable description of what went wrong
error.name
The error type: TypeError, RangeError, SyntaxError, etc.
error.stack
A stack trace showing where the error originated
catch (error) { if (error instanceof TypeError) { console.error('Type problem:', error.message); } else if (error.name === 'AbortError') { console.log('Request was cancelled.'); } else { throw error; // re-throw unknown errors } }

Common Mistakes

Missing await
Calling an async function without await means errors escape your try/catch entirely.
Empty catch block
Writing catch (e) { } silently swallows errors. Always log or handle the error.
Forgetting response.ok
fetch() doesn't reject on HTTP errors. A 404 resolves normally: you must check !res.ok yourself.

Summary: Error Handling Patterns

Pattern Best For Catches Errors?
try/catch + await Sequential async operations ✓ Yes
.then().catch() Single promise chains ✓ Yes
Promise.all + try/catch Parallel operations (fail-fast) ✓ Yes
Promise.allSettled Parallel operations (partial results) Per-promise status
await without try/catch Never do this in production ✕ No

Question 1 of 5

What happens if you use await inside a function that is not marked as async?

Question 2 of 5

If the server returns a 404 Not Found response, what happens?

Question 3 of 5

What is the purpose of the finally block in a try/catch/finally statement?

Question 4 of 5

If fetchUser() rejects with an error, which of the following is true?

Question 5 of 5

Which of the following is a dangerous anti-pattern in async error handling?