Walidacja i obsługa błędów
Waliduj dane przychodzących żądań i zwracaj spójne, dobrze ustrukturyzowane odpowiedzi błędów w bezserwerowych API zbudowanych za pomocą Workers i Deno.
Walidacja i obsługa błędów to bezpłatna lekcja Edge Computing with Cloudflare Workers & Deno na CoddyKit. To lekcja 3 z 3. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Edge Computing with Cloudflare Workers & Deno, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 3 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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:
400Bad Request, invalid body401Unauthorized, missing auth404Not Found422Unprocessable Entity, semantic validation failure500Internal 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.
Często zadawane pytania
Czy lekcja „Walidacja i obsługa błędów” jest bezpłatna?
Tak — pełny tekst „Walidacja i obsługa błędów” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Edge Computing with Cloudflare Workers & Deno, przejdź na CoddyKit PRO. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 3 lekcji w sumie.
Co nauczysz się w „Walidacja i obsługa błędów”?
Waliduj dane przychodzących żądań i zwracaj spójne, dobrze ustrukturyzowane odpowiedzi błędów w bezserwerowych API zbudowanych za pomocą Workers i Deno. Ćwiczysz Edge Computing with Cloudflare Workers & Deno z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Edge Computing with Cloudflare Workers & Deno?
Nie wymagamy żadnego doświadczenia. Edge Computing with Cloudflare Workers & Deno w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 3.
Ile czasu zajmuje lekcja „Walidacja i obsługa błędów”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Edge Computing with Cloudflare Workers & Deno?
Tak. Każda lekcja Edge Computing with Cloudflare Workers & Deno zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Projektowanie interfejsów API RESTful
- Routing i middleware
- Walidacja i obsługa błędów