Skip to content

Merge Develop into Main #9

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 8 commits 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
48 changes: 48 additions & 0 deletions .github/workflows/cd.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Release and Publish

on:
workflow_run:
workflows: ["Quality Checks"]
types:
- completed
branches: [main]
workflow_dispatch:

jobs:
release-and-publish:
name: Release and Publish
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
issues: write
pull-requests: write

steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
registry-url: "https://registry.npmjs.org"
always-auth: true
token: ${{ secrets.NPM_TOKEN }}

- name: Install dependencies
run: npm ci

- name: Build Package
run: npm run build

- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release
72 changes: 72 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
name: Quality Checks

on:
pull_request:
branches: [main, develop]
push:
branches: [main]

jobs:
test-and-lint:
name: Test and Lint
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'

- name: Install dependencies
run: npm ci

- name: Run linting
run: npm run lint

- name: Build package
run: npm run build

- name: Run tests with coverage
run: npm run test:coverage

- name: Upload coverage report
if: success()
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
if-no-files-found: error

verify-release:
name: Verify Release
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'

- name: Install dependencies
run: npm ci

- name: Build package
run: npm run build

- name: Semantic-release dry-run
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release --dry-run
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Node.js
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# TypeScript
*.tsbuildinfo

# Logs
logs
*.log
logs/*.log

# Dependency directories
jspm_packages/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# dotenv environment variables file
.env

# Mac system files
.DS_Store

# Coverage directory
coverage/
1 change: 1 addition & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
npx --no -- commitlint --edit ${1}
7 changes: 7 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
npm audit --omit=dev || (
echo '🚨 npm audit found vulnerabilities!'
echo 'Review the audit report above and fix any high-severity issues.'
exit 1
)

npx lint-staged
6 changes: 6 additions & 0 deletions .lintstagedrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
"(src|tests|scripts|config|.)/**/*.{js,ts,json,yml}": [
"eslint --cache --fix",
"jest --bail --passWithNoTests --findRelatedTests",
],
};
7 changes: 7 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
examples/
tests/
__tests__/
src/
tsconfig.json
.gitignore
.npmignore
18 changes: 18 additions & 0 deletions .releaserc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export default {
branches: ["main"],
plugins: [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/changelog",
"@semantic-release/npm",
"@semantic-release/github",
[
"@semantic-release/git",
{
assets: ["package.json", "package-lock.json", "CHANGELOG.md"],
message:
"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}",
},
],
],
};
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
6 changes: 6 additions & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
extends: ["@commitlint/config-conventional"],
rules: {
"body-max-line-length": [0],
},
};
Loading
Loading