How do you handle errors in asynchronous operations?
Interview answer
Handle promise failures with .catch(), use try/catch around awaited work, check response.ok for HTTP errors, and choose Promise.allSettled when parallel tasks must fail independently. In React, keep loading, error, and data states explicit and cancel obsolete requests with AbortController.
Exceptions and promise rejections have different boundaries
A synchronous throw reaches the nearest active try/catch. A promise rejection reaches a rejection handler, or becomes a thrown exception at an await inside an async function. Returning an unawaited promise from a try block does not let that catch observe its later rejection.
async function readJson(url, signal) {try {const response = await fetch(url, { signal });if (!response.ok) {const error = new Error(`HTTP ${response.status}`);error.status = response.status;throw error;}return await response.json(); // await lets this catch observe parsing errors} catch (error) {if (signal?.aborted) throw error;throw new Error(`Unable to read ${url}`, { cause: error });}}
A connection failure rejects fetch; a 404 or 500 normally resolves with an unsuccessful Response. Check response.ok. Even a successful response can contain invalid JSON. Preserve the original error as cause when adding context instead of throwing a generic string or converting every failure into an empty list. An empty list means a successful request with no results, which is a different UI state.
A later callback runs outside the outer catch
// Problem: the outer catch has finished when the callback executes.try {setTimeout(() => { throw new Error('Later failure'); }, 0);} catch (error) {console.error('This does not catch the timer failure', error);}// Correction: catch within the callback's own execution.setTimeout(() => {try {JSON.parse('invalid JSON');} catch (error) {console.error('Timer task failed', error);}}, 0);
For promise-based work, attach .catch() to the chain or await it. A chain's final catch handles failures returned or thrown by its earlier handlers; an unreturned nested promise is outside that chain. React error boundaries handle rendering failures, rather than ordinary timer, event-handler, or request rejections; handle those at their async boundary.
Choose parallel failure semantics
// Both results are required to build this view.try {const [users, permissions] = await Promise.all([readJson('/api/users'),readJson('/api/permissions'),]);console.log({ users, permissions });} catch (error) {console.error('Cannot build the view', error);}// Independent panels may succeed or fail separately.const results = await Promise.allSettled([readJson('/api/users'),readJson('/api/activity'),]);results.forEach(result => {if (result.status === 'fulfilled') console.log(result.value);else console.error(result.reason);});
Promise.all rejects as soon as an input rejects, but does not cancel the other operations. Abort them explicitly if cancellation is desired and supported. Promise.allSettled waits for each input to settle and reports each outcome, which supports partial results. With an ordinary valid array of promises it resolves even when tasks reject; malformed iterables can still reject the aggregate.
A request-driven React interface
import { useEffect, useState } from 'react';export function UserList({ teamId }) {const [view, setView] = useState({ status: 'loading', users: [] });const [attempt, setAttempt] = useState(0);useEffect(() => {let active = true;const controller = new AbortController();setView({ status: 'loading', users: [] });async function load() {try {const response = await fetch(`/api/teams/${teamId}/users`, {signal: controller.signal,});if (!response.ok) throw new Error(`HTTP ${response.status}`);const users = await response.json();if (!Array.isArray(users)) throw new Error('Invalid user-list response');if (active) setView({ status: users.length ? 'success' : 'empty', users });} catch (error) {if (!active || controller.signal.aborted) return;console.error('User list failed', error);setView({ status: 'error', users: [] });}}void load();return () => { active = false; controller.abort(); };}, [teamId, attempt]);if (view.status === 'loading') return <p role="status">Loading users…</p>;if (view.status === 'error') return <div><p role="alert">Unable to load users.</p><button onClick={() => setAttempt(value => value + 1)}>Try again</button></div>;if (view.status === 'empty') return <p>No users in this team.</p>;return <ul>{view.users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;}
The endpoint is assumed to return an array of { id, name } users. Network, HTTP, parsing, and shape failures enter the error state. A team change or unmount aborts the old request and marks it inactive. Cleanup cancellation should not be displayed as a failure. The guard also blocks old completions from overwriting the new team. The retry button starts a fresh read; it does not blindly retry a mutation. For a user-visible Cancel button, model a separate canceled/idle state so the interface does not stay loading forever. A timeout may abort the same request mechanism, but should be classified as a timeout and shown when appropriate rather than hidden as voluntary cancellation.
Retry decisions and useful diagnostics
Retry a bounded number of transient failures with backoff and jitter. Respect service throttling and Retry-After where applicable. Authentication, validation errors, and malformed responses usually need a correction rather than the same request repeated. A failed mutation may already have committed on the server; use a server-supported idempotency key or reconciliation before resubmitting. A browser network error alone cannot prove that the operation never reached the server.
Record the operation, HTTP status if known, safe request/correlation ID, and original error/cause. Avoid logging tokens, personal data, or unrestricted response bodies. Keep the user message actionable and separate from technical diagnostics.
Interview follow-ups
- What does this catch cover, and which work escapes it?
- Does a rejected aggregate stop the other requests?
- How do you distinguish an empty result, cancellation, timeout, and failure?
- Is repeating this request safe if the server already accepted it?
Reviewed 1 October 2026 against MDN: using fetch, Promise.all, and React useEffect.
A production-ready async error checklist
A strong interview answer goes beyond catching an exception. Explain which failures you expect, what the user sees, and whether the operation is safe to retry.
- Separate network failures, non-2xx HTTP responses, parsing errors, and user cancellation.
- Preserve the original error or cause so logs remain useful after adding a user-friendly message.
- Retry only transient failures, use backoff, and never retry an unsafe mutation blindly.
- Prevent stale requests from overwriting newer React state by aborting or ignoring obsolete work.
Related interview practice
Related React Ecosystem interview topics
Continue with nearby questions from the same topic cluster.