การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด
ตรวจสอบข้อมูลคำขอขาเข้าและส่งคืนการตอบกลับข้อผิดพลาดที่สม่ำเสมอและมีโครงสร้างชัดเจนในเอพีไอแบบไร้เซิร์ฟเวอร์ที่สร้างด้วย Workers และ Deno
การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด เป็นบทเรียน Edge Computing with Cloudflare Workers & Deno ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Edge Computing with Cloudflare Workers & Deno ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด”
ตรวจสอบข้อมูลคำขอขาเข้าและส่งคืนการตอบกลับข้อผิดพลาดที่สม่ำเสมอและมีโครงสร้างชัดเจนในเอพีไอแบบไร้เซิร์ฟเวอร์ที่สร้างด้วย Workers และ Deno คุณปฏิบัติ Edge Computing with Cloudflare Workers & Deno ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Edge Computing with Cloudflare Workers & Deno หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Edge Computing with Cloudflare Workers & Deno บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน
บทเรียน “การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Edge Computing with Cloudflare Workers & Deno นี้ได้ไหม
ได้ บทเรียน Edge Computing with Cloudflare Workers & Deno ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การออกแบบ API แบบ RESTful
- การกำหนดเส้นทางและมิดเดิลแวร์
- การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด