0
# Error Management
1
2
HTTP error creation and handling system with status codes and structured error responses for microservices.
3
4
## Capabilities
5
6
### HttpError Class
7
8
Custom error class that extends the standard Error with HTTP-specific properties for status codes and error chaining.
9
10
```typescript { .api }
11
/**
12
* HTTP-specific error class with status code support
13
*/
14
class HttpError extends Error {
15
constructor(message: string);
16
17
/** HTTP status code to send with error response */
18
statusCode?: number;
19
20
/** Reference to original error if this error wraps another */
21
originalError?: Error;
22
}
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { HttpError } from "micro";
29
30
// Create basic HTTP error
31
const error = new HttpError("User not found");
32
error.statusCode = 404;
33
34
// Create with original error reference
35
const dbError = new Error("Connection timeout");
36
const httpError = new HttpError("Database unavailable");
37
httpError.statusCode = 503;
38
httpError.originalError = dbError;
39
40
// Throw in handler
41
const handler = async (req, res) => {
42
const userId = req.url?.split("/").pop();
43
44
if (!userId) {
45
const error = new HttpError("User ID is required");
46
error.statusCode = 400;
47
throw error;
48
}
49
50
const user = await findUser(userId);
51
if (!user) {
52
const error = new HttpError("User not found");
53
error.statusCode = 404;
54
throw error;
55
}
56
57
return user;
58
};
59
```
60
61
### Create Error Function
62
63
Utility function for creating HttpError instances with status codes and original error references in a single call.
64
65
```typescript { .api }
66
/**
67
* Creates HttpError with status code and original error reference
68
* @param code - HTTP status code for the error
69
* @param message - Human-readable error message
70
* @param original - Original error that caused this HTTP error
71
* @returns HttpError instance with all properties set
72
*/
73
function createError(code: number, message: string, original: Error): HttpError;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { createError } from "micro";
80
81
// Basic error creation
82
const error = createError(400, "Invalid email format", new Error("Validation failed"));
83
84
// In request handlers
85
const validationHandler = async (req, res) => {
86
try {
87
const data = await json(req);
88
89
if (!data.email || !data.email.includes("@")) {
90
throw createError(400, "Valid email is required", new Error("Email validation failed"));
91
}
92
93
return { success: true };
94
} catch (parseError) {
95
if (parseError instanceof Error && parseError.message.includes("JSON")) {
96
throw createError(400, "Invalid JSON in request body", parseError);
97
}
98
throw parseError;
99
}
100
};
101
102
// Database operation errors
103
const databaseHandler = async (req, res) => {
104
try {
105
const result = await database.query("SELECT * FROM users");
106
return result;
107
} catch (dbError) {
108
if (dbError.code === "ECONNREFUSED") {
109
throw createError(503, "Service temporarily unavailable", dbError as Error);
110
}
111
if (dbError.code === "EACCES") {
112
throw createError(500, "Internal server error", dbError as Error);
113
}
114
throw createError(500, "Database operation failed", dbError as Error);
115
}
116
};
117
```
118
119
## Error Handling Patterns
120
121
### Validation Errors
122
123
```typescript
124
import { createError, json } from "micro";
125
126
const validateUser = (userData: any) => {
127
const errors: string[] = [];
128
129
if (!userData.name || userData.name.trim().length < 2) {
130
errors.push("Name must be at least 2 characters");
131
}
132
133
if (!userData.email || !userData.email.includes("@")) {
134
errors.push("Valid email is required");
135
}
136
137
if (!userData.age || userData.age < 18) {
138
errors.push("Age must be 18 or older");
139
}
140
141
if (errors.length > 0) {
142
throw createError(400, `Validation failed: ${errors.join(", ")}`, new Error("Validation"));
143
}
144
};
145
146
const userHandler = async (req, res) => {
147
const userData = await json(req);
148
validateUser(userData);
149
150
// Process valid user data
151
return { success: true, user: userData };
152
};
153
```
154
155
### Authentication Errors
156
157
```typescript
158
import { createError } from "micro";
159
160
const authenticateUser = (token: string) => {
161
if (!token) {
162
throw createError(401, "Authentication token required", new Error("Missing token"));
163
}
164
165
if (!token.startsWith("Bearer ")) {
166
throw createError(401, "Invalid token format", new Error("Invalid format"));
167
}
168
169
const jwt = token.substring(7);
170
try {
171
return verifyToken(jwt);
172
} catch (error) {
173
throw createError(401, "Invalid or expired token", error as Error);
174
}
175
};
176
177
const protectedHandler = async (req, res) => {
178
const token = req.headers.authorization;
179
const user = authenticateUser(token as string);
180
181
return { message: `Hello ${user.name}`, data: "protected content" };
182
};
183
```
184
185
### Rate Limiting Errors
186
187
```typescript
188
import { createError } from "micro";
189
190
const rateLimitMap = new Map<string, { count: number; resetTime: number }>();
191
192
const checkRateLimit = (clientId: string, limit: number = 100, windowMs: number = 60000) => {
193
const now = Date.now();
194
const clientData = rateLimitMap.get(clientId);
195
196
if (!clientData || now > clientData.resetTime) {
197
rateLimitMap.set(clientId, { count: 1, resetTime: now + windowMs });
198
return;
199
}
200
201
if (clientData.count >= limit) {
202
const resetIn = Math.ceil((clientData.resetTime - now) / 1000);
203
throw createError(
204
429,
205
`Rate limit exceeded. Try again in ${resetIn} seconds`,
206
new Error("Rate limit")
207
);
208
}
209
210
clientData.count++;
211
};
212
213
const rateLimitedHandler = async (req, res) => {
214
const clientIp = req.socket.remoteAddress || "unknown";
215
checkRateLimit(clientIp);
216
217
return { message: "Request processed successfully" };
218
};
219
```
220
221
### Error Response Format
222
223
```typescript
224
import { sendError, createError } from "micro";
225
226
const consistentErrorHandler = async (req, res) => {
227
try {
228
// Your application logic
229
throw new Error("Something went wrong");
230
} catch (error) {
231
// Convert to structured HTTP error
232
const httpError = createError(
233
500,
234
"Internal server error occurred",
235
error as Error
236
);
237
238
// Send structured error response
239
sendError(req, res, httpError);
240
}
241
};
242
243
// Custom error formatting
244
const customErrorHandler = async (req, res) => {
245
try {
246
// Your application logic
247
} catch (error) {
248
if (error instanceof HttpError) {
249
send(res, error.statusCode || 500, {
250
error: {
251
message: error.message,
252
code: error.statusCode,
253
timestamp: new Date().toISOString(),
254
path: req.url
255
}
256
});
257
} else {
258
send(res, 500, {
259
error: {
260
message: "Internal server error",
261
code: 500,
262
timestamp: new Date().toISOString(),
263
path: req.url
264
}
265
});
266
}
267
}
268
};
269
```