Careeroza
Status Codes
The Codes You Will Use Most
| Code | Name | When ShopEase returns it |
|---|---|---|
| 200 | OK | GET, PUT, PATCH succeeded |
| 201 | Created | POST created a product (NestJS default for @Post) |
| 204 | No Content | DELETE succeeded, nothing to return |
| 400 | Bad Request | Validation failed (price is negative) |
| 401 | Unauthorized | No or invalid login token |
| 403 | Forbidden | Logged in but not allowed (customer tries admin route) |
| 404 | Not Found | Product id does not exist |
| 409 | Conflict | Email already registered |
| 429 | Too Many Requests | Rate limit hit |
| 500 | Internal Server Error | A bug or crash on the server |
Status Codes as Code
Example
NestJS has an HttpStatus enum so you never type magic numbers. Here is a tiny version of the same idea, plus a helper that tells you the class of a code:
enum HttpStatus {
OK = 200,
CREATED = 201,
NO_CONTENT = 204,
BAD_REQUEST = 400,
NOT_FOUND = 404,
INTERNAL_SERVER_ERROR = 500,
}
function kind(code: number): string {
if (code >= 500) return 'server error';
if (code >= 400) return 'client error';
if (code >= 300) return 'redirect';
if (code >= 200) return 'success';
return 'informational';
}
for (const code of [HttpStatus.CREATED, HttpStatus.NO_CONTENT, HttpStatus.NOT_FOUND, HttpStatus.INTERNAL_SERVER_ERROR]) {
console.log(code, HttpStatus[code], '->', kind(code));
}Output
201 CREATED -> success 204 NO_CONTENT -> success 404 NOT_FOUND -> client error 500 INTERNAL_SERVER_ERROR -> server error