Saltar al contenido principal
Curso/Asincronía/Manejo de Errores Async
Volver a Asincronía

Asincronía — Leccion 3

·15 min

Manejo de Errores Async

Captura errores en codigo asíncrono.

Errores en async/await

typescript
async function division(a: number, b: number): Promise<number> {
  if (b === 0) {
    throw new Error("No se puede dividir por cero");
  }
  return a / b;
}

try {
  const resultado = await division(10, 0);
  console.log(resultado);
} catch (error) {
  console.error(error.message);
}

Patrón try/catch

typescript
async function cargarDatos() {
  try {
    const res = await fetch("/api/datos");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (error) {
    if (error instanceof Error) {
      console.error("Error de red:", error.message);
    }
    return null;
  }
}

Re-lanzar errores

typescript
async function procesar(id: number) {
  try {
    const datos = await fetch(`/api/${id}`);
    return await datos.json();
  } catch (error) {
    // Log y re-lanzar
    console.error("Error procesando:", id);
    throw error;
  }
}

Función helper

typescript
async function to<T>(promise: Promise<T>): Promise<[T | null, Error | null]> {
  try {
    const data = await promise;
    return [data, null];
  } catch (error) {
    return [null, error as Error];
  }
}

// Uso
const [usuario, error] = await to(fetchUsuario(1));
if (error) {
  console.error(error.message);
}

Ejercicio pratico

Crea una función to() que capture errores y retorne [dato, error].

exercise.ts
Loading...
Resultado

Haz clic en "Ejecutar" para ver el resultado...

Curso de TypeScript — Aprende desde cero