Skip to main content
Saved

Pattern Resilience Advanced

Error Handling

Your app should catch errors where it calls your APIs, and show users a clear message that tells them what they can do next, such as trying again.

Examples
React, Vue and native web
Read
5 min

The problem

If an error is never caught, users can end up looking at a loading spinner that never stops, which is worse than any error message. They might wait and refresh, without ever finding out that the request failed five seconds ago.

The pattern

My rule is that every async operation gets explicit error handling. I wrap it in try-catch and store the error in state, so users get a useful message that explains what happened and what they can do about it.

Problem

I’ve debugged many production issues where the console showed a clear error but users saw nothing helpful. Network timeouts and malformed JSON both ended up as silent failures or as the dreaded “something went wrong” message that doesn’t help anyone.

Error handling is often inconsistent within the same app, where one component retries automatically while another shows an error with no retry button. Plenty of errors aren’t even logged, because someone swallowed them with an empty catch block.

Solution

The right response depends on the error. A 404 means the resource doesn’t exist, so retrying won’t help, and a “not found” message makes more sense. A network timeout is usually temporary, so a retry button is useful. After a 401, the user needs to log in, so it’s better to redirect them than to show a generic error. A 422 means the input failed validation, so you can highlight the fields that need fixing.

You should also log each error with enough context to debug it later, such as the user ID and the request parameters. The message users see should tell them what to do, like “Check your connection and try again,” instead of cryptic developer output like “Error: undefined is not a function.”

If you can, it’s better for the app to keep partly working than to fail completely. If fresh data fails to load but you have cached data, you can show the cached data with a “Last updated 5 minutes ago” note.

Example

These examples follow one failed request from start to finish. A fetch helper classifies the error, a component responds differently to each type, and a shared handler does the logging and picks the message. Retrying automatically and catching render errors each have their own page, Retry and Error Boundary.

Classifying Errors

With a plain fetch call, it’s hard to tell one kind of failure from another, because the call rejects with a TypeError when the network fails, and it resolves normally for a 404 or a 500. This helper turns each failure into an APIError with a status and a code, so the calling code can tell them apart. The helper also cancels the request after five seconds, so a request that never completes becomes a timeout error instead of a spinner that never stops.

class APIError extends Error {
  constructor(message, { status = 0, code, fields } = {}) {
    super(message);
    this.status = status; // 0 when no response arrived
    this.code = code;
    this.fields = fields; // Per-field messages from a 422
  }
}

async function request(url, options = {}) {
  let response;
  try {
    response = await fetch(url, { ...options, signal: AbortSignal.timeout(5000) });
  } catch (error) {
    // fetch only rejects when it didn't get a response
    const code = error.name === 'TimeoutError' ? 'TIMEOUT' : 'NETWORK_ERROR';
    throw new APIError('No response from the server', { code });
  }

  if (!response.ok) {
    const body = await response.json().catch(() => ({}));
    throw new APIError(body.message || 'Request failed', {
      status: response.status,
      code: body.code,
      fields: body.fields
    });
  }
  return response.json();
}

const fetchUser = (id) => request(`/api/users/${id}`);
const saveUser = (user) => request(`/api/users/${user.id}`, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(user)
});

Responding by Error Type

The component stores the error object in state and responds according to its status. For a 401 it redirects to the login page, for a 404 it shows a “not found” message with no retry button, and for a timeout, a network error, or a 5xx response it shows a “Try again” button, because those requests might work on a second attempt.

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [attempt, setAttempt] = useState(0);

  useEffect(() => {
    async function loadUser() {
      try {
        setLoading(true);
        setError(null);
        setUser(await fetchUser(userId));
      } catch (err) {
        if (err.status === 401) {
          // The spinner stays up while the browser redirects
          window.location.assign('/login');
          return;
        }
        window.Sentry?.captureException(err, { extra: { userId } });
        setError(err);
      }
      setLoading(false);
    }
    loadUser();
  }, [userId, attempt]);

  if (loading) return <Spinner />;
  if (error?.status === 404) return <p>This user doesn't exist.</p>;
  if (error) {
    // Status 0 is a network error or a timeout
    const canRetry = error.status === 0 || error.status >= 500;
    return (
      <div role="alert">
        <p>We couldn't load this profile.</p>
        {canRetry && <button onClick={() => setAttempt(a => a + 1)}>Try again</button>}
      </div>
    );
  }
  return <div>{user.name}</div>;
}

A 422 only comes back when the user submits something, so the form’s submit handler checks for it. The messages for each field go into their own state, and the handler doesn’t change the values the user typed, so the user can fix the one field and submit again.

function ProfileForm({ user }) {
  const [values, setValues] = useState(user);
  const [fieldErrors, setFieldErrors] = useState({});
  const [error, setError] = useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    try {
      await saveUser(values);
    } catch (err) {
      if (err.status === 422) setFieldErrors(err.fields); // { email: 'Already in use' }
      else setError(err);
    }
  }

  // The inputs render from values, with fieldErrors[name] under each one
}

Shared Error Handler

Once several components catch errors, each one ends up with its own logging and its own wording. A shared handler logs every error the same way, and returns the message and whether a retry makes sense, so a catch block only needs setError(handleError(err, { userId })).

const messages = {
  NETWORK_ERROR: 'Check your connection and try again.',
  TIMEOUT: 'The server took too long to respond.',
  401: 'Please log in to continue.',
  403: "You don't have permission to view this.",
  404: "We couldn't find what you were looking for.",
  422: 'Some of the fields need fixing.'
};

function handleError(error, context = {}) {
  console.error(error, context);
  window.Sentry?.captureException(error, { extra: context });

  return {
    status: error.status,
    message: messages[error.code] ?? messages[error.status] ?? 'Something went wrong on our side.',
    canRetry: error.status === 0 || error.status >= 500
  };
}

You can still log any error that your code didn’t catch by listening for the error and unhandledrejection events on window.

Graceful Degradation

If the fetch fails, this function falls back to cached data, so users can keep working with data that’s out of date but still useful.

async function fetchUserWithFallback(userId) {
  try {
    return await fetchUser(userId);
  } catch (error) {
    console.warn('Fetch failed, using cache:', error);
    const cached = getCachedUser(userId);
    return cached ? { ...cached, stale: true } : { id: userId, name: 'User', stale: true };
  }
}

Benefits

  • Users see what went wrong instead of staring at a page that has stopped responding or a spinner that never ends.
  • Users can recover from temporary failures, such as a flaky connection, with a “Try again” button.
  • Production issues are much easier to debug when errors are logged with full context about user actions and request parameters.
  • When the main API is down, the app can stay partly usable by showing cached data.
  • Each type of error can get the right response, so an auth failure redirects to the login page and a validation error highlights the fields that need fixing.
  • Users don’t lose their work when a submit fails, because the form keeps what they typed, and they can fix a field or retry without entering it all again.

Tradeoffs

  • Try-catch blocks add boilerplate, and your main logic can get buried under error handling code.
  • An empty catch block like catch (e) {} makes the error disappear from the console, but then nothing gets logged, and production problems become much harder to debug.
  • You have to decide what to do with each type of error, such as whether to retry or fail and whether to show a modal or an inline message, and those decisions take time.
  • A shared handler tends to treat similar errors the same way, but some 500 errors need a specific response instead of a generic toast.
  • An error thrown from an async callback never gets to an error boundary, so you have to catch it and render the error UI yourself, or pass it to the boundary as the Error Boundary page shows.
  • Users and developers need different error messages, so you often end up writing two versions of each one, a friendly one for users and a detailed one for the team.
  • Logging too much fills your monitoring tools with noise, and a temporary failure usually shouldn’t wake someone up at 3am.
  • Falling back to cached data can confuse users who don’t realize the information is out of date, so the UI needs to make that obvious.

Summary

With good error handling, a failed request shows users a clear message instead of breaking the app, and they can usually recover from it. The app treats the errors users can fix differently from the ones a developer has to fix, and it always gives users something they can do next.

See also

Next in Resilience Loading State A loading state shows users that an asynchronous operation is still in progress, so they know the app is working.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.