0Pricing
Edge Computing with Cloudflare Workers & Deno · Lezione

Validazione e gestione degli errori

Validate i dati delle richieste in ingresso e restituite risposte di errore coerenti e ben strutturate nelle API serverless realizzate con Workers e Deno.

Validazione e gestione degli errori è una lezione Edge Computing with Cloudflare Workers & Deno gratuita su CoddyKit. Questa è la lezione 3 di 3. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Edge Computing with Cloudflare Workers & Deno, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Edge Computing with Cloudflare Workers & Deno include 3 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Validazione e gestione degli errori» è gratuita?

Sì — il testo completo di «Validazione e gestione degli errori» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Edge Computing with Cloudflare Workers & Deno, passa a CoddyKit PRO. Il corso Edge Computing with Cloudflare Workers & Deno include 3 lezioni in totale.

Cosa imparerò in «Validazione e gestione degli errori»?

Validate i dati delle richieste in ingresso e restituite risposte di errore coerenti e ben strutturate nelle API serverless realizzate con Workers e Deno. Eserciti Edge Computing with Cloudflare Workers & Deno con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Edge Computing with Cloudflare Workers & Deno?

Non è richiesta alcuna esperienza precedente. Edge Computing with Cloudflare Workers & Deno su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 3.

Quanto tempo richiede la lezione «Validazione e gestione degli errori»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Edge Computing with Cloudflare Workers & Deno?

Sì. Ogni lezione Edge Computing with Cloudflare Workers & Deno include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Progettazione di API RESTful
  2. Routing e middleware
  3. Validazione e gestione degli errori
← Torna a Edge Computing with Cloudflare Workers & Deno