0Pricing
Edge Computing with Cloudflare Workers & Deno · Lección

Validación y gestión de errores

Valide los datos de las solicitudes entrantes y devuelva respuestas de error coherentes y bien estructuradas en API serverless creadas con Workers y Deno.

Validación y gestión de errores es una lección gratuita de Edge Computing with Cloudflare Workers & Deno en CoddyKit. Esta es la lección 3 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Edge Computing with Cloudflare Workers & Deno, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Edge Computing with Cloudflare Workers & Deno incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Validate Input?

Never trust client input. A robust API validates every incoming payload before acting on it.

Validation prevents:

  • Corrupt data entering your store
  • Crashes from missing fields
  • Security issues like injection

At the edge, validation also fails fast, saving CPU and downstream calls.

Parsing the Request Body

Most APIs accept JSON. Parse it safely, malformed JSON throws.

async function readJson(request) {
  try {
    return await request.json();
  } catch {
    return null;
  }
}

Manual Field Validation

For simple schemas you can validate by hand.

Check required fields and types before continuing.

function validateUser(body) {
  const errors = [];
  if (typeof body.name !== 'string') errors.push('name is required');
  if (typeof body.age !== 'number') errors.push('age must be a number');
  return errors;
}

Schema Validation with Zod

For larger APIs, a schema library like Zod (which runs on both Workers and Deno) is cleaner and gives typed output.

import { z } from 'zod';

const UserSchema = z.object({
  name: z.string().min(1),
  age: z.number().int().positive()
});

safeParse for Graceful Errors

Use safeParse so validation never throws, you inspect the result instead.

const result = UserSchema.safeParse(body);
if (!result.success) {
  // result.error.issues describes what failed
}

Consistent Error Response Shape

Return errors in a predictable JSON shape so clients can parse them reliably.

function errorResponse(message, status, details) {
  return new Response(
    JSON.stringify({ error: message, details: details || null }),
    { status, headers: { 'Content-Type': 'application/json' } }
  );
}

Choosing the Right Status Code

Match HTTP status to the failure type:

  • 400 Bad Request, invalid body
  • 401 Unauthorized, missing auth
  • 404 Not Found
  • 422 Unprocessable Entity, semantic validation failure
  • 500 Internal Server Error, unexpected

A try/catch Safety Net

Wrap handlers in try/catch so an unexpected throw becomes a clean 500 instead of a crash.

export default {
  async fetch(request, env) {
    try {
      return await handle(request, env);
    } catch (err) {
      return errorResponse('Internal Server Error', 500);
    }
  }
};

Validating Query & Path Params

Body is not the only untrusted input, query strings and path params need checks too.

const url = new URL(request.url);
const page = Number(url.searchParams.get('page') || '1');
if (!Number.isInteger(page) || page < 1) {
  return errorResponse('Invalid page', 400);
}

Avoid Leaking Internal Details

In production, never send stack traces or raw error messages to clients.

Log the full error internally, return a generic message externally.

catch (err) {
  console.error(err);
  return errorResponse('Something went wrong', 500);
}

Best Practices Summary

Solid validation and error handling means:

  • Validate body, query, and params
  • Use a schema library for complex inputs
  • Return a consistent error shape
  • Pick correct status codes
  • Catch everything and hide internals

Quick Check

Which HTTP status best fits a request whose JSON is well-formed but fails a business validation rule?

Recap

You now validate untrusted input and return clean errors:

  • Safely parse bodies and params
  • Validate manually or with Zod's safeParse
  • Use a consistent error JSON shape and correct status codes
  • Wrap handlers in try/catch and hide internal details

Reliable validation is what separates a toy API from a production-grade one.

Preguntas frecuentes

¿La lección «Validación y gestión de errores» es gratis?

Sí — el texto completo de «Validación y gestión de errores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Edge Computing with Cloudflare Workers & Deno, actualiza a CoddyKit PRO. El curso de Edge Computing with Cloudflare Workers & Deno incluye 3 lecciones en total.

¿Qué aprenderé en «Validación y gestión de errores»?

Valide los datos de las solicitudes entrantes y devuelva respuestas de error coherentes y bien estructuradas en API serverless creadas con Workers y Deno. Practicas Edge Computing with Cloudflare Workers & Deno con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Edge Computing with Cloudflare Workers & Deno?

No se requiere experiencia previa. Edge Computing with Cloudflare Workers & Deno en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 3.

¿Cuánto tiempo toma la lección «Validación y gestión de errores»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Edge Computing with Cloudflare Workers & Deno?

Sí. Cada lección de Edge Computing with Cloudflare Workers & Deno incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Diseño de API RESTful
  2. Enrutamiento y middleware
  3. Validación y gestión de errores
← Volver a Edge Computing with Cloudflare Workers & Deno