Handling API Response Errors Gracefully in TypeScript for Real-World Applications

Learn how to handle API response errors gracefully in TypeScript to build robust, reliable real-world applications.

When working with APIs in TypeScript, handling errors gracefully is crucial to ensure a smooth user experience and maintainable code. This article will guide you through the basics of detecting, managing, and displaying API errors clearly using TypeScript.

First, it’s important to understand the possible types of errors you might encounter. APIs can return HTTP error codes like 400, 404, or 500, or your code might encounter network issues like timeouts. Handling these errors separately helps you provide meaningful feedback to users.

Here's a simple example of how to fetch data from an API and handle errors using TypeScript’s type system and modern JavaScript features like async/await and try/catch blocks.

typescript
interface ApiResponse<T> {
  data: T | null;
  error: string | null;
}

async function fetchUser(userId: number): Promise<ApiResponse<{ id: number; name: string }>> {
  try {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);

    if (!response.ok) {
      // Handle HTTP errors
      return { data: null, error: `Request failed with status ${response.status}` };
    }

    const data = await response.json();
    return { data, error: null };
  } catch (error) {
    // Handle network or unexpected errors
    if (error instanceof Error) {
      return { data: null, error: error.message };
    }

    return { data: null, error: 'An unknown error occurred' };
  }
}

In this example, we define a generic ApiResponse interface to represent the response shape containing either data or an error message. The fetchUser function calls an API to fetch user data, checks if the HTTP response status is OK, and returns either the data or an error string.

When using this function, you can check if an error occurred and handle it accordingly, for example, by showing a message to the user or retrying the request.

typescript
async function displayUser(userId: number) {
  const response = await fetchUser(userId);

  if (response.error) {
    console.error('API Error:', response.error);
    alert(`Error: ${response.error}`);
    return;
  }

  console.log('User data:', response.data);
  alert(`User found: ${response.data?.name}`);
}

To summarize, handling API response errors gracefully in TypeScript involves: - Using try/catch blocks to catch network or unexpected errors - Checking the HTTP response status for server or client errors - Using TypeScript interfaces to clearly represent success or error states - Presenting meaningful messages to the user when an error occurs By following these steps, your applications will be more reliable and easier to maintain.