Skip to content

Commit d00b492

Browse files
authored
chore: add docs (#8)
1 parent 7d43817 commit d00b492

File tree

9 files changed

+327
-24
lines changed

9 files changed

+327
-24
lines changed

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Junjie Wu
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# handle-http-errors
2+
3+
HTTP error handling library with TypeScript support, providing error classes, handlers, and middleware support.
4+
5+
## ☘️ Features
6+
7+
- Error Classes - Built-in HTTP error classes with type support
8+
- Error Handler - Flexible error handling with standardized responses
9+
- Middleware Support - Ready-to-use Express middleware
10+
- TypeScript Support - Full type safety with TypeScript
11+
12+
## 📥 Installation
13+
14+
```bash
15+
npm install handle-http-errors
16+
# or
17+
yarn add handle-http-errors
18+
# or
19+
pnpm add handle-http-errors
20+
```
21+
22+
## 📖 Usage
23+
24+
### 🔧 Error Handler
25+
26+
```typescript
27+
import express from 'express';
28+
import { errorHandler, ValidationError } from 'handle-http-errors';
29+
30+
const app = express();
31+
32+
app.post('/users', async (req, res) => {
33+
try {
34+
const { email } = req.body;
35+
if (!email) {
36+
throw new ValidationError('Email is required');
37+
}
38+
} catch (error) {
39+
return errorHandler(error, res);
40+
}
41+
});
42+
```
43+
44+
### 🌐 Middleware
45+
46+
```typescript
47+
import express from 'express';
48+
import { errorMiddleware, NotFoundError } from 'handle-http-errors';
49+
50+
const app = express();
51+
52+
app.get('/users/:id', (req, res, next) => {
53+
try {
54+
throw new NotFoundError('User not found', { id: req.params.id });
55+
} catch (error) {
56+
next(error);
57+
}
58+
});
59+
60+
app.use(errorMiddleware());
61+
```
62+
63+
## 🗂️ Error Classes
64+
65+
```typescript
66+
import {
67+
HttpError, // Base error class
68+
ValidationError, // 400 - Validation errors
69+
BadRequestError, // 400 - Malformed requests
70+
UnauthorizedError, // 401 - Authentication errors
71+
ForbiddenError, // 403 - Authorization errors
72+
NotFoundError, // 404 - Resource not found
73+
InternalServerError // 500 - Server errors
74+
} from 'handle-http-errors';
75+
```
76+
77+
## 📋 Error Response Format
78+
79+
```typescript
80+
{
81+
status: number; // HTTP status code
82+
code: string; // Error code (e.g., 'VALIDATION_ERROR')
83+
message: string; // Error message
84+
timestamp: string; // ISO timestamp
85+
details?: object; // Optional error details
86+
stack?: string; // Stack trace (development only)
87+
}
88+
```
89+
90+
## ⚙️ Configuration
91+
92+
```typescript
93+
// Middleware options
94+
interface ErrorHandlerOptions {
95+
includeStack?: boolean; // Include stack traces
96+
onError?: (error: unknown) => void; // Error callback
97+
}
98+
99+
// Using with options
100+
app.use(errorMiddleware({
101+
includeStack: process.env.NODE_ENV !== 'production',
102+
onError: (error) => console.error(error)
103+
}));
104+
```
105+
106+
## 🔍 Development vs Production
107+
108+
Development Mode (`NODE_ENV !== 'production'`):
109+
- Detailed error messages
110+
- Stack traces (when enabled)
111+
- Error details included
112+
113+
Production Mode (`NODE_ENV === 'production'`):
114+
- Generic error messages
115+
- No stack traces
116+
- Limited error details
117+
118+
## 📚 Examples
119+
120+
Check out the [examples](https://github.com/junjie-w/handle-http-errors/tree/main/examples) directory for detailed usage examples.
121+
122+
## 📄 License
123+
124+
MIT

examples/README.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# handle-http-errors Examples
2+
3+
Examples of using [handle-http-errors](https://www.npmjs.com/package/handle-http-errors) with different approaches.
4+
5+
## 🚀 Running Examples
6+
7+
```bash
8+
npm install
9+
10+
npm run dev:handler # Error handler usage (Port 3001)
11+
npm run dev:middleware # Middleware usage (Port 3002)
12+
npm run dev:custom # Custom middlewares usage (Port 3003)
13+
```
14+
15+
### 🔧 Error Handler Example (Port 3001)
16+
17+
```bash
18+
npm run dev:handler
19+
```
20+
21+
Test endpoints:
22+
23+
```bash
24+
# Test NotFoundError
25+
curl http://localhost:3001/with-handler
26+
27+
# Test ValidationError with invalid product ID
28+
curl http://localhost:3001/products/abc
29+
30+
# Test NotFoundError with valid product ID
31+
curl http://localhost:3001/products/123
32+
33+
# Test ValidationError with invalid product data
34+
curl -X POST \
35+
-H "Content-Type: application/json" \
36+
-d '{"name":"","price":-10}' \
37+
http://localhost:3001/products
38+
39+
# Test InternalServerError with valid product data
40+
curl -X POST \
41+
-H "Content-Type: application/json" \
42+
-d '{"name":"Test Product","price":10}' \
43+
http://localhost:3001/products
44+
```
45+
46+
### 🌐 Middleware Example (Port 3002)
47+
48+
```bash
49+
npm run dev:middleware
50+
```
51+
52+
Test endpoints:
53+
54+
```bash
55+
# Test NotFoundError
56+
curl http://localhost:3002/with-middleware
57+
58+
# Test ValidationError with invalid user ID
59+
curl http://localhost:3002/users/abc
60+
61+
# Test NotFoundError with valid user ID
62+
curl http://localhost:3002/users/123
63+
64+
# Test ValidationError with missing data
65+
curl -X POST \
66+
-H "Content-Type: application/json" \
67+
-d '{}' \
68+
http://localhost:3002/users/register
69+
70+
# Test ValidationError with invalid email
71+
curl -X POST \
72+
-H "Content-Type: application/json" \
73+
-d '{"email":"invalid-email","username":"test"}' \
74+
http://localhost:3002/users/register
75+
76+
# Test ValidationError with short username
77+
curl -X POST \
78+
-H "Content-Type: application/json" \
79+
-d '{"email":"[email protected]","username":"a"}' \
80+
http://localhost:3002/users/register
81+
82+
# Test InternalServerError with valid data
83+
curl -X POST \
84+
-H "Content-Type: application/json" \
85+
-d '{"email":"[email protected]","username":"testuser"}' \
86+
http://localhost:3002/users/register
87+
```
88+
89+
### 🛠️ Custom Middleware Example (Port 3003)
90+
91+
```bash
92+
npm run dev:custom-middleware
93+
```
94+
95+
Test endpoints:
96+
97+
```bash
98+
# Test UnauthorizedError without token
99+
curl http://localhost:3003/users/123
100+
101+
# Test UnauthorizedError with invalid token
102+
curl -H "Authorization: invalid-token" \
103+
http://localhost:3003/users/123
104+
105+
# Test ValidationError with valid token but invalid ID
106+
curl -H "Authorization: valid-token" \
107+
http://localhost:3003/users/abc
108+
109+
# Test NotFoundError with valid token and valid ID
110+
curl -H "Authorization: valid-token" \
111+
http://localhost:3003/users/123
112+
113+
# Test UnauthorizedError in registration
114+
curl -X POST \
115+
-H "Content-Type: application/json" \
116+
-d '{"email":"[email protected]","username":"test"}' \
117+
http://localhost:3003/users/register
118+
119+
# Test ValidationError in registration
120+
curl -X POST \
121+
-H "Authorization: valid-token" \
122+
-H "Content-Type: application/json" \
123+
-d '{"email":"invalid-email","username":"a"}' \
124+
http://localhost:3003/users/register
125+
126+
# Test ForbiddenError when creating admin
127+
curl -X POST \
128+
-H "Authorization: valid-token" \
129+
-H "Content-Type: application/json" \
130+
-d '{"email":"[email protected]","username":"admin"}' \
131+
"http://localhost:3003/users/register?role=admin"
132+
133+
# Test successful registration
134+
curl -X POST \
135+
-H "Authorization: valid-token" \
136+
-H "Content-Type: application/json" \
137+
-d '{"email":"[email protected]","username":"testuser"}' \
138+
http://localhost:3003/users/register
139+
```
140+
141+
Each example demonstrates different aspects of error handling:
142+
- Error Handler: Direct usage of errorHandler
143+
- Middleware: Global error handling with middleware
144+
- Custom Middleware: Creating custom error-throwing middlewares

examples/package-lock.json

Lines changed: 11 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
},
1010
"dependencies": {
1111
"express": "^4.18.2",
12-
"http-error-handler": "file:../"
12+
"handle-http-errors": "file:../"
1313
},
1414
"devDependencies": {
1515
"@types/express": "^4.17.17",

examples/src/withCustomMiddleware.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
ForbiddenError,
66
ValidationError,
77
NotFoundError,
8-
} from "http-error-handler";
8+
} from "handle-http-errors";
99

1010
const app = express();
1111
app.use(express.json());

examples/src/withHandler.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
errorHandler,
44
NotFoundError,
55
ValidationError,
6-
} from "http-error-handler";
6+
} from "handle-http-errors";
77

88
const app = express();
99
app.use(express.json());

examples/src/withMiddleware.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
errorMiddleware,
44
NotFoundError,
55
ValidationError,
6-
} from "http-error-handler";
6+
} from "handle-http-errors";
77

88
const app = express();
99
app.use(express.json());

0 commit comments

Comments
 (0)