Skip to content
intermediate

Error Handling with Async/Await

Properly handle errors in async functions using try/catch.

interface ApiResponse<T> {
  data: T;
  error?: string;
}

async function fetchData(url: string): Promise<string> {
  if (url.includes('error')) {
    throw new Error('Network error');
  }
  return `Data from ${url}`;
}

async function safeFetch(url: string): Promise<ApiResponse<string>> {
  ___ {
    const data = await fetchData(url);
    return { ____ };
  } catch (error) {
    return {
      data: '',
      error: __________...
    };
  }
}
0/3 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code