Skip to content

chore: add docs #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Junjie Wu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
124 changes: 124 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# handle-http-errors

HTTP error handling library with TypeScript support, providing error classes, handlers, and middleware support.

## ☘️ Features

- Error Classes - Built-in HTTP error classes with type support
- Error Handler - Flexible error handling with standardized responses
- Middleware Support - Ready-to-use Express middleware
- TypeScript Support - Full type safety with TypeScript

## 📥 Installation

```bash
npm install handle-http-errors
# or
yarn add handle-http-errors
# or
pnpm add handle-http-errors
```

## 📖 Usage

### 🔧 Error Handler

```typescript
import express from 'express';
import { errorHandler, ValidationError } from 'handle-http-errors';

const app = express();

app.post('/users', async (req, res) => {
try {
const { email } = req.body;
if (!email) {
throw new ValidationError('Email is required');
}
} catch (error) {
return errorHandler(error, res);
}
});
```

### 🌐 Middleware

```typescript
import express from 'express';
import { errorMiddleware, NotFoundError } from 'handle-http-errors';

const app = express();

app.get('/users/:id', (req, res, next) => {
try {
throw new NotFoundError('User not found', { id: req.params.id });
} catch (error) {
next(error);
}
});

app.use(errorMiddleware());
```

## 🗂️ Error Classes

```typescript
import {
HttpError, // Base error class
ValidationError, // 400 - Validation errors
BadRequestError, // 400 - Malformed requests
UnauthorizedError, // 401 - Authentication errors
ForbiddenError, // 403 - Authorization errors
NotFoundError, // 404 - Resource not found
InternalServerError // 500 - Server errors
} from 'handle-http-errors';
```

## 📋 Error Response Format

```typescript
{
status: number; // HTTP status code
code: string; // Error code (e.g., 'VALIDATION_ERROR')
message: string; // Error message
timestamp: string; // ISO timestamp
details?: object; // Optional error details
stack?: string; // Stack trace (development only)
}
```

## ⚙️ Configuration

```typescript
// Middleware options
interface ErrorHandlerOptions {
includeStack?: boolean; // Include stack traces
onError?: (error: unknown) => void; // Error callback
}

// Using with options
app.use(errorMiddleware({
includeStack: process.env.NODE_ENV !== 'production',
onError: (error) => console.error(error)
}));
```

## 🔍 Development vs Production

Development Mode (`NODE_ENV !== 'production'`):
- Detailed error messages
- Stack traces (when enabled)
- Error details included

Production Mode (`NODE_ENV === 'production'`):
- Generic error messages
- No stack traces
- Limited error details

## 📚 Examples

Check out the [examples](https://github.com/junjie-w/handle-http-errors/tree/main/examples) directory for detailed usage examples.

## 📄 License

MIT
144 changes: 144 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# handle-http-errors Examples

Examples of using [handle-http-errors](https://www.npmjs.com/package/handle-http-errors) with different approaches.

## 🚀 Running Examples

```bash
npm install

npm run dev:handler # Error handler usage (Port 3001)
npm run dev:middleware # Middleware usage (Port 3002)
npm run dev:custom # Custom middlewares usage (Port 3003)
```

### 🔧 Error Handler Example (Port 3001)

```bash
npm run dev:handler
```

Test endpoints:

```bash
# Test NotFoundError
curl http://localhost:3001/with-handler

# Test ValidationError with invalid product ID
curl http://localhost:3001/products/abc

# Test NotFoundError with valid product ID
curl http://localhost:3001/products/123

# Test ValidationError with invalid product data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"","price":-10}' \
http://localhost:3001/products

# Test InternalServerError with valid product data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Test Product","price":10}' \
http://localhost:3001/products
```

### 🌐 Middleware Example (Port 3002)

```bash
npm run dev:middleware
```

Test endpoints:

```bash
# Test NotFoundError
curl http://localhost:3002/with-middleware

# Test ValidationError with invalid user ID
curl http://localhost:3002/users/abc

# Test NotFoundError with valid user ID
curl http://localhost:3002/users/123

# Test ValidationError with missing data
curl -X POST \
-H "Content-Type: application/json" \
-d '{}' \
http://localhost:3002/users/register

# Test ValidationError with invalid email
curl -X POST \
-H "Content-Type: application/json" \
-d '{"email":"invalid-email","username":"test"}' \
http://localhost:3002/users/register

# Test ValidationError with short username
curl -X POST \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","username":"a"}' \
http://localhost:3002/users/register

# Test InternalServerError with valid data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","username":"testuser"}' \
http://localhost:3002/users/register
```

### 🛠️ Custom Middleware Example (Port 3003)

```bash
npm run dev:custom-middleware
```

Test endpoints:

```bash
# Test UnauthorizedError without token
curl http://localhost:3003/users/123

# Test UnauthorizedError with invalid token
curl -H "Authorization: invalid-token" \
http://localhost:3003/users/123

# Test ValidationError with valid token but invalid ID
curl -H "Authorization: valid-token" \
http://localhost:3003/users/abc

# Test NotFoundError with valid token and valid ID
curl -H "Authorization: valid-token" \
http://localhost:3003/users/123

# Test UnauthorizedError in registration
curl -X POST \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","username":"test"}' \
http://localhost:3003/users/register

# Test ValidationError in registration
curl -X POST \
-H "Authorization: valid-token" \
-H "Content-Type: application/json" \
-d '{"email":"invalid-email","username":"a"}' \
http://localhost:3003/users/register

# Test ForbiddenError when creating admin
curl -X POST \
-H "Authorization: valid-token" \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","username":"admin"}' \
"http://localhost:3003/users/register?role=admin"

# Test successful registration
curl -X POST \
-H "Authorization: valid-token" \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","username":"testuser"}' \
http://localhost:3003/users/register
```

Each example demonstrates different aspects of error handling:
- Error Handler: Direct usage of errorHandler
- Middleware: Global error handling with middleware
- Custom Middleware: Creating custom error-throwing middlewares
18 changes: 11 additions & 7 deletions examples/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
},
"dependencies": {
"express": "^4.18.2",
"http-error-handler": "file:../"
"handle-http-errors": "file:../"
},
"devDependencies": {
"@types/express": "^4.17.17",
Expand Down
2 changes: 1 addition & 1 deletion examples/src/withCustomMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
ForbiddenError,
ValidationError,
NotFoundError,
} from "http-error-handler";
} from "handle-http-errors";

const app = express();
app.use(express.json());
Expand Down
2 changes: 1 addition & 1 deletion examples/src/withHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
errorHandler,
NotFoundError,
ValidationError,
} from "http-error-handler";
} from "handle-http-errors";

const app = express();
app.use(express.json());
Expand Down
2 changes: 1 addition & 1 deletion examples/src/withMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
errorMiddleware,
NotFoundError,
ValidationError,
} from "http-error-handler";
} from "handle-http-errors";

const app = express();
app.use(express.json());
Expand Down
Loading
Loading