HTTP Status Codes
4xx ka matlab hai CLIENT ki galti aur 5xx ka matlab SERVER ki galti. Sabse common galti hai har cheez par 200 bhejna aur body mein {"success": false} likhna — isse client ka error handling, monitoring aur retry logic sab tut jaata hai.
Important distinctions: 401 (tum kaun ho, pata nahi — login karo) vs 403 (pata hai tum kaun ho, lekin permission nahi), 400 (malformed request) vs 422 (syntax sahi, semantics galat), 404 (nahi mila) vs 410 (tha, ab hamesha ke liye chala gaya).
res.status(200).json(user); // OK
res.status(201).json(created); // Created
res.status(400).json({ error: "Invalid body" });
res.status(401).json({ error: "Login required" }); // authentication
res.status(403).json({ error: "Not allowed" }); // authorization
res.status(429).json({ error: "Too many requests" });- 4xx client ki galti, 5xx server ki galti — status code jhoot mat bolo
- 401 authentication ke liye, 403 authorization ke liye
- Har response par 200 bhejna client ka error handling tod deta hai
200 OK, 201 Created (naye resource ke saath Location header), 204 No Content (delete/update ke baad bina body), 400 Bad Request, 401 Unauthorized (login chahiye), 403 Forbidden (permission nahi), 404 Not Found, 409 Conflict (duplicate email), 422 Unprocessable Entity (validation fail), 429 Too Many Requests, 500 Internal Server Error.
if (await User.exists({ email }))
return res.status(409).json({ error: "Email already registered" });Poore API mein error response ka EK hi shape rakho — client ka error handling tabhi simple rehta hai. Ek achha shape hai: code (machine-readable), message (human-readable), aur optional details (field-wise validation errors).
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Request body is invalid",
"details": [{ "field": "email", "issue": "must be a valid email" }]
}
}