验证与错误处理
验证传入的请求数据,并在使用 Workers 和 Deno 构建的无服务器接口中返回一致且结构良好的错误响应。
验证与错误处理 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「验证与错误处理」课时是免费的吗?
是的 — 「验证与错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 3 节课。
「验证与错误处理」这节课中我会学到什么?
验证传入的请求数据,并在使用 Workers 和 Deno 构建的无服务器接口中返回一致且结构良好的错误响应。 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「验证与错误处理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?
能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设计 RESTful API
- 路由与中间件
- 验证与错误处理