0Pricing
Edge Computing with Cloudflare Workers & Deno · Lesson

Validation & Error Handling

Validate incoming request data and return consistent, well-structured error responses in serverless APIs built with Workers and Deno.

Validation & Error Handling is a free Edge Computing with Cloudflare Workers & Deno lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Edge Computing with Cloudflare Workers & Deno learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Validation & Error Handling” lesson free?

Yes — the full text of “Validation & Error Handling” is free to read here on the web, and the Edge Computing with Cloudflare Workers & Deno course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Edge Computing with Cloudflare Workers & Deno course, upgrade to CoddyKit PRO.

What will I learn in “Validation & Error Handling”?

Validate incoming request data and return consistent, well-structured error responses in serverless APIs built with Workers and Deno. You practise Edge Computing with Cloudflare Workers & Deno with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Edge Computing with Cloudflare Workers & Deno?

No prior experience is required. Edge Computing with Cloudflare Workers & Deno on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Validation & Error Handling” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Edge Computing with Cloudflare Workers & Deno lesson?

Yes. Every Edge Computing with Cloudflare Workers & Deno lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Designing RESTful APIs
  2. Routing & Middleware
  3. Validation & Error Handling
← Back to Edge Computing with Cloudflare Workers & Deno