0Pricing
Edge Computing with Cloudflare Workers & Deno · Lektion

Validierung und Fehlerbehandlung

Validieren Sie eingehende Anfragedaten und geben Sie konsistente, gut strukturierte Fehlerantworten in serverlosen APIs zurück, die mit Workers und Deno erstellt wurden.

Validierung und Fehlerbehandlung ist eine kostenlose Edge Computing with Cloudflare Workers & Deno-Lektion auf CoddyKit. Dies ist Lektion 3 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Edge Computing with Cloudflare Workers & Deno-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Edge Computing with Cloudflare Workers & Deno-Kurs umfasst insgesamt 3 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Häufig gestellte Fragen

Ist die Lektion „Validierung und Fehlerbehandlung“ kostenlos?

Ja — der vollständige Text von „Validierung und Fehlerbehandlung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Edge Computing with Cloudflare Workers & Deno-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Edge Computing with Cloudflare Workers & Deno-Kurs umfasst insgesamt 3 Lektionen.

Was lerne ich in „Validierung und Fehlerbehandlung“?

Validieren Sie eingehende Anfragedaten und geben Sie konsistente, gut strukturierte Fehlerantworten in serverlosen APIs zurück, die mit Workers und Deno erstellt wurden. Du übst Edge Computing with Cloudflare Workers & Deno mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Edge Computing with Cloudflare Workers & Deno zu starten?

Keine Vorkenntnisse erforderlich. Edge Computing with Cloudflare Workers & Deno auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 3.

Wie lange dauert die Lektion „Validierung und Fehlerbehandlung“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Edge Computing with Cloudflare Workers & Deno-Lektion Code schreiben und ausführen?

Ja. Jede Edge Computing with Cloudflare Workers & Deno-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. RESTful APIs entwerfen
  2. Routing und Middleware
  3. Validierung und Fehlerbehandlung
← Zurück zu Edge Computing with Cloudflare Workers & Deno