تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
شجرة أخطاء الـ API (AppError ومشتقاته) مقابل الأخطاء الغير متوقعة. معيار RFC 9457: application/problem+json بـ type و title و status و detail و instance، و traceId للربط بالـ logs. تحويل أخطاء express.json و Zod و Postgres (23505 و 23503) لأكواد صح، و 404 كـ error، وإزاي ما تسرّبش stack ولا تفاصيل الـ database.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. لو كل route بيرد بالـ errors بشكل مختلف، مرة error، ومرة message، ومرة HTML، الـ frontend هيتعب، والـ mobile app هيتعب أكتر. الحل حاجتين: تصنيف واضح: كل خطأ متوقع ليه class بـ status و type. وشكل موحّد للرد، وفيه معيار رسمي اسمه Problem Details، RFC nine four five seven. errors dot js فيه AppError، و functions صغيرة بتعمل الأنواع المشهورة. problem dot js: الـ error handler الوحيد في الـ app. لو AppError: نحوّله لـ problem بالحقول الرسمية: type، و title، و status، و detail. لو JSON بايز من express dot json، ده error ليه type معروف: four hundred. غير كده: خطأ مش متوقع، يعني bug. نسجّله كامل في الـ logs، ونرد برسالة عامة بس. وفي الآخر instance: الـ path، و traceId: رقم الـ request، علشان الدعم الفني يلاقي الـ log. والـ content type: application problem plus json.
server dot js: request id. routes بترمي errors عادي بـ throw، ومن غير try. boom فيه bug حقيقي. وفي الآخر: أي route مش موجود بيعمل next بـ NotFound، فحتى الـ four oh four بيعدّي على نفس الـ handler. نشغّل.
import express from "express";
import crypto from "node:crypto";
import { NotFound, Conflict } from "./errors.js";
import { problemHandler } from "./problem.js";
const app = express();
app.use((req, res, next) => {
req.id = crypto.randomUUID().slice(0, 8);
next();
});
app.use(express.json());
const emails = new Set(["[email protected]"]);
app.get("/courses/:id", (req, res) => {
throw NotFound(`الكورس ${req.params.id}`);
});
app.post("/users", (req, res) => {
if (emails.has(req.body.email)) throw Conflict("الإيميل متسجل قبل كده");
res.status(201).json({ ok: true });
});
app.get("/boom", async () => {
const db = undefined;
return db.query("select 1");
});
app.use((req, res, next) => next(NotFound(`${req.method} ${req.path}`)));
app.use(problemHandler);
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /courses/7
← 404 Not Found
connection: keep-alive
content-length: 179
content-type: application/problem+json; charset=utf-8
etag: W/"b3-DrUqfHWHPrcKFd7bHPFM1kwp2ZY"
keep-alive: timeout=5
x-powered-by: Express
{
"type": "https://api.example.com/problems/not-found",
"title": "مش موجود",
"status": 404,
"detail": "الكورس 7 مش موجود",
"instance": "/courses/7",
"traceId": "3681696a"
}
→ POST /users
{"email":"[email protected]"}
← 409 Conflict
{
"type": "https://api.example.com/problems/conflict",
"title": "تعارض",
"status": 409,
"detail": "الإيميل متسجل قبل كده",
"instance": "/users",
"traceId": "8c73f907"
}
→ POST /users
{"email": "oops
← 400 Bad Request
{
"type": "https://api.example.com/problems/bad-json",
"title": "JSON بايز",
"status": 400,
"instance": "/users",
"traceId": "bfe69146"
}
→ GET /boom
[a720ebd7] TypeError: Cannot read properties of undefined (reading 'query') | at file:///home/you/my-backend/server.js:24:13
← 500 Internal Server Error
{
"type": "about:blank",
"title": "حصلت مشكلة عندنا",
"status": 500,
"instance": "/boom",
"traceId": "a720ebd7"
}
→ GET /nope
← 404
…الكورس: four oh four، والـ content type problem plus json، والـ type URL، والـ title والـ detail، والـ instance والـ traceId. الإيميل المكرر: four oh nine conflict. JSON مقطوع: four hundred. boom: الـ client شاف حصلت مشكلة عندنا بس، والـ log في الـ server فيه رقم الـ request والـ TypeError كامل. و nope: نفس الشكل. الـ type ده URL ممكن تعمله صفحة docs بتشرح الخطأ وحله، والـ clients بتقارن بيه بدل ما تقرا الرسالة.
قاعدتين أمان مهمين جدًّا هنا. عمرك ما ترجّع stack trace للـ client: بيكشف أسماء ملفات ومكتبات وإصدارات، والمهاجم بيبني عليها. ورسايل الـ database زي ما هي ممنوعة برضه. Postgres لما يرفض إيميل مكرر، الـ detail بتاعه بيقول اسم العمود والقيمة، يعني ممكن حد يعرف مين متسجل عندك. الصح: الـ log فيه كل حاجة، والـ response فيه اللي الـ client محتاجه بس. التحدي: كل error ليه مكان. ZodError: four twenty two، ومعاها list بالحقول. unique violation من Postgres، code اتنين تلاتة خمسة صفر خمسة: four oh nine، ومن غير ما الـ detail بتاع Postgres يتسرب. foreign key: four twenty two. body كبير: four thirteen. الشروط وحالات الاختبار في الكومنت.
زوّد في problemHandler: ZodError ← 422 + errors، و 23505 ← 409، و 23503 ← 422، و entity.too.large ← 413، من غير تسريب تفاصيل.
الحل. نقلنا التحويل لـ function اسمها toProblem، بترجّع problem أو null. AppError زي ما هو. ZodError بالـ issues كـ field و message. الأكواد بتاعة Postgres بأرقامها. و entity too large. ولو null: يبقى bug، نسجّل ونرد five hundred. وفي server dot js: routes للتجربة، و express dot json بـ limit مِيّة byte على route واحد. نشغّل.
import express from "express";
import crypto from "node:crypto";
import { z } from "zod";
import { NotFound } from "./errors.js";
import { problemHandler } from "./problem.js";
const app = express();
app.use((req, res, next) => {
req.id = crypto.randomUUID().slice(0, 8);
next();
});
app.get("/zod", () => {
z.object({ email: z.email() }).parse({ email: "x" });
});
app.get("/dup", () => {
const e = new Error("duplicate key value violates unique constraint");
e.code = "23505";
e.detail = "Key (email)=([email protected]) already exists.";
throw e;
});
app.post("/big", express.json({ limit: "100b" }), (req, res) => res.json({ ok: true }));
app.use((req, res, next) => next(NotFound(`${req.method} ${req.path}`)));
app.use(problemHandler);
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ GET /zod
← 422 Unprocessable Entity
{
"type": "https://api.example.com/problems/validation",
"title": "البيانات مش صح",
"status": 422,
"errors": [
{
"field": "email",
"message": "Invalid email address"
}
],
"instance": "/zod",
"traceId": "c40bcfd8"
}
→ GET /dup
← 409 Conflict
{
"type": "https://api.example.com/problems/conflict",
"title": "متسجل قبل كده",
"status": 409,
"instance": "/dup",
"traceId": "6db5fa1e"
}
→ POST /big
{"text":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx …
← 413 Payload Too Large
{
"type": "https://api.example.com/problems/too-large",
"title": "الـ body كبير",
"status": 413,
"instance": "/big",
"traceId": "61cf2369"
}
→ GET /nope
← 404 Not Found
{
"type": "https://api.example.com/problems/not-found",
"title": "مش موجود",
"status": 404,
"detail": "GET /nope مش موجود",
"instance": "/nope",
"traceId": "5e44f639"
}zod: four twenty two بالحقل email. dup: four oh nine، ومفيش ولا كلمة من رسالة Postgres. big: four thirteen. nope: four oh four. الدرس الجاي: الـ CORS والـ cookies، وليه المتصفح بيرفض requests شغالة تمام في Postman.
import { z } from "zod";
import { AppError } from "./errors.js";
const BASE = "https://api.example.com/problems/";
function toProblem(err) {
if (err instanceof AppError) {
return { type: BASE + err.type, title: err.title, status: err.status, detail: err.detail, ...err.extra };
}
if (err instanceof z.ZodError) {
return {
type: BASE + "validation",
title: "البيانات مش صح",
status: 422,
errors: err.issues.map((i) => ({ field: i.path.join("."), message: i.message })),
};
}
if (err.code === "23505") return { type: BASE + "conflict", title: "متسجل قبل كده", status: 409 };
if (err.code === "23503") return { type: BASE + "invalid-reference", title: "مرجع مش موجود", status: 422 };
if (err.type === "entity.parse.failed") return { type: BASE + "bad-json", title: "JSON بايز", status: 400 };
if (err.type === "entity.too.large") return { type: BASE + "too-large", title: "الـ body كبير", status: 413 };
return null;
}
export function problemHandler(err, req, res, next) {
let p = toProblem(err);
if (!p) {
console.error(`[${req.id}] ${err.stack.split("\n").slice(0, 2).join(" | ")}`);
p = { type: "about:blank", title: "حصلت مشكلة عندنا", status: 500 };
}
p.instance = req.originalUrl;
p.traceId = req.id;
res.status(p.status).type("application/problem+json").json(p);
}03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errorsانت هنا
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem