Skip to content

fix: update tests and docs #12

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 21, 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
106 changes: 54 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
# handle-http-errors

HTTP error handling library with TypeScript support, providing error classes, handlers, and middleware support.
Type-safe HTTP error handling package providing error classes, standardized responses, error handler, and built-in Express middleware support.

## ☘️ Features
Available as [NPM package](https://www.npmjs.com/package/handle-http-errors).

- 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
## 🚂 Features

## 📥 Installation
- Error Classes
- Error Handler
- Express Middleware Support
- TypeScript Support

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

## 📖 Usage
## ☘️ Usage

### 🔧 Error Handler

Expand All @@ -41,7 +33,7 @@ app.post('/users', async (req, res) => {
});
```

### 🌐 Middleware
### 🌐 Express Middleware

```typescript
import express from 'express';
Expand All @@ -60,17 +52,44 @@ app.get('/users/:id', (req, res, next) => {
app.use(errorMiddleware());
```

## ⚙️ Configuration

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

// Use with handler
app.post('/users', async (req, res) => {
try {
throw new ValidationError('Invalid data');
} catch (error) {
return errorHandler(error, res, {
includeStack: process.env.NODE_ENV !== 'production',
onError: (error) => console.error(error)
});
}
});

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

## 🗂️ 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
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';
```

Expand All @@ -87,38 +106,21 @@ import {
}
```

## ⚙️ Configuration
## 🪺 Examples

```typescript
// Middleware options
interface ErrorHandlerOptions {
includeStack?: boolean; // Include stack traces
onError?: (error: unknown) => void; // Error callback
}
Check out the [examples](https://github.com/junjie-w/handle-http-errors/tree/main/examples) directory for detailed usage examples:

// Using with options
app.use(errorMiddleware({
includeStack: process.env.NODE_ENV !== 'production',
onError: (error) => console.error(error)
}));
```bash
git clone https://github.com/junjie-w/handle-http-errors.git
cd handle-http-errors/examples
npm install

# Try different examples
npm run dev:handler # Error handler usage
npm run dev:middleware # Express middleware usage
npm run dev:custom-middleware # Creating custom error-throwing middlewares
```

## 🔍 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
31 changes: 13 additions & 18 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
# handle-http-errors Examples

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

## 🚀 Running Examples
## 🚂 Run 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)
npm run dev:handler # Error handler usage
npm run dev:middleware # Express middleware usage
npm run dev:custom-middleware # Creating custom error-throwing middlewares
```

### 🔧 Error Handler Example (Port 3001)
### 🔧 Error Handler Example

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

Test endpoints:
#### 🌱 Test endpoints:

```bash
# Test NotFoundError
Expand All @@ -43,13 +43,13 @@ curl -X POST \
http://localhost:3001/products
```

### 🌐 Middleware Example (Port 3002)
### 🌐 Express Middleware Example

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

Test endpoints:
#### 🌱 Test endpoints:

```bash
# Test NotFoundError
Expand All @@ -73,7 +73,7 @@ curl -X POST \
-d '{"email":"invalid-email","username":"test"}' \
http://localhost:3002/users/register

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

### 🛠️ Custom Middleware Example (Port 3003)
### 🛠️ Creating custom error-throwing middlewares

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

Test endpoints:
#### 🌱 Test endpoints:

```bash
# Test UnauthorizedError without token
Expand Down Expand Up @@ -123,7 +123,7 @@ curl -X POST \
-d '{"email":"invalid-email","username":"a"}' \
http://localhost:3003/users/register

# Test ForbiddenError when creating admin
# Test ForbiddenError when creating admin users
curl -X POST \
-H "Authorization: valid-token" \
-H "Content-Type: application/json" \
Expand All @@ -137,8 +137,3 @@ curl -X POST \
-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
Loading
Loading