├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ └── bug_report.md └── test.yaml ├── .gitignore ├── .husky └── pre-commit ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── index.ts ├── package.json ├── src └── asyncErrorHandler.ts ├── test └── asyncErrorHandler.test.ts └── tsconfig.json /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [pacifiquem] 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[Bug]: " 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Screenshots** 20 | If applicable, add screenshots to help explain your problem. 21 | 22 | **Desktop (please complete the following information):** 23 | - OS: [e.g. iOS] 24 | - Node Versiond: [e.g. v20.0.0] 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/test.yaml: -------------------------------------------------------------------------------- 1 | name: Run Tests on Pull Request 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@v2 15 | 16 | - name: Set up Node.js 17 | uses: actions/setup-node@v3 18 | with: 19 | node-version: '18' 20 | 21 | - name: Install dependencies 22 | run: yarn 23 | 24 | - name: Run tests 25 | run: yarn test 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Node.js 2 | node_modules/ 3 | 4 | # npm 5 | npm-debug.log 6 | *.lock 7 | node_modules/ 8 | package-lock.json 9 | /yarn-error.log 10 | yarn-debug.log* 11 | 12 | # Editor directories and files 13 | .idea/ 14 | .vscode/ 15 | *.suo 16 | *.ntvs* 17 | *.njsproj 18 | *.sln 19 | *.sw? 20 | 21 | # build output 22 | 23 | .tgz 24 | /dist 25 | /build -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | yarn test 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | <pacifiquemurangwa001@gmail.com>. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | <https://www.contributor-covenant.org/faq>. Translations are available at 128 | <https://www.contributor-covenant.org/translations>. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to node-async-handler 2 | 3 | Thank you for considering contributing to node-async-handler! We welcome your input and appreciate your efforts to make this middleware even better. 4 | 5 | ## How to Contribute 6 | 7 | 1. Fork the Repository: 8 | Fork the repository to your GitHub account and clone it to your local machine. 9 | 10 | 2. Install Dependencies: 11 | Run npm install to install the necessary dependencies. 12 | 13 | 3. Make Changes: 14 | Implement your changes or add new features. Ensure that your code follows the project's coding standards. 15 | 16 | 4. Test Your Changes: 17 | Run the existing tests or add new tests to verify that your changes work as expected. 18 | 19 | 5. Submit a Pull Request: 20 | Once you are satisfied with your changes, submit a pull request to the main repository. Clearly describe the purpose of your pull request and any notable changes. 21 | 22 | ## Code Style Guidelines 23 | 24 | Please adhere to the following code style guidelines: 25 | 26 | - Use consistent indentation (preferably 2 or 4 spaces). 27 | - Follow the existing naming conventions. 28 | - Keep your code concise and readable. 29 | 30 | ## Reporting Issues 31 | 32 | If you encounter any issues or have suggestions for improvements, please open an issue on the GitHub repository. Clearly describe the problem or enhancement, including any relevant details. 33 | 34 | > **Note** : In case you didn't follow all things listed in this file, your issue or pull request will be reject immediately. 35 | 36 | ## License 37 | 38 | By contributing to node-async-handler, you agree that your contributions will be licensed under the MIT License. Please refer to the [LICENSE](https://github.com/pacifiquem/node-async-handler/blob/main/LICENSE) file for details. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | =========== 3 | 4 | Copyright (c) 2023 - Present M.Pac 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # node-async-handler 2 | 3 | Async Error Handling Middleware for Express with ESM Support 4 | 5 | This middleware helps you eliminate the need for ```try-catch``` blocks throughout your Express application, streamlining error handling and improving code readability. 6 | 7 | > **Note** : This is made specifically for ExpressJS projects. 8 | 9 | ## Usage 10 | 11 | To use ```node-async-handler```, simply wrap your async functions in the asyncHandler middleware: 12 | 13 | ```ts 14 | // For ESM 15 | import pkg from 'node-async-handler'; 16 | const { asyncHandler } = pkg; 17 | 18 | // For CommonJS 19 | const { asyncHandler } = require('node-async-handler'); 20 | 21 | express.get('/', asyncHandler(async (req: Request, res: Response, next: NextFunction) => { 22 | const result = await someAsyncFunction(); 23 | res.json(result); 24 | })); 25 | ``` 26 | 27 | In case of an error, the middleware automatically calls ```next(error)```, allowing centralized error handling in your Express app. 28 | 29 | ## Importing 30 | 31 | > **Note** : To import ```node-async-handler``` in ESM: 32 | > 33 | > ```ts 34 | > import pkg from 'node-async-handler'; 35 | > const { asyncHandler } = pkg; 36 | >``` 37 | 38 | > **Note** : To import ```node-async-handler``` in CommonJS: 39 | > 40 | > ```ts 41 | > const { asyncHandler } = require('node-async-handler'); 42 | >``` 43 | 44 | ## License 45 | 46 | This project is licensed under the MIT License. See the [LICENSE file](https://github.com/pacifiquem/node-async-handler/blob/main/LICENSE) for details. 47 | 48 | <p align="right" style="color: gray;">Author: MURANGWA Pacifique</p> 49 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | If you believe you've found a security vulnerability in our programming language, please help us by responsibly disclosing the details to us privately, before making them public. We are committed to quickly addressing and fixing any reported vulnerabilities. 6 | > **Note** : Do not use Github Issues to report vulnerability, in case you've found any use these steps to report it: 7 | 8 | ### How to Report a Vulnerability 9 | 10 | Please report security vulnerabilities to us via email at: pacifiquemurangwa001@gmail.com 11 | 12 | 13 | When reporting security issues, kindly provide the following information: 14 | 15 | - **Description of the Vulnerability**: A clear and concise description of the security vulnerability. 16 | 17 | - **Steps to Reproduce**: Provide detailed steps to reproduce the vulnerability. 18 | 19 | - **Expected Behavior**: Describe what you expected to happen. 20 | 21 | - **Actual Behavior**: Explain what actually happened. 22 | 23 | - **Attachments**: If applicable, include any proof-of-concept code or screenshots that demonstrate the vulnerability. 24 | 25 | ### What to Expect 26 | 27 | Once we receive your report, we will acknowledge your email within 72 hours. Our security team will then review and prioritize the reported issues. We will keep you informed of the progress and notify you when the vulnerability has been addressed. 28 | 29 | We appreciate your contributions to our security and are grateful for your assistance in keeping our programming language secure. 30 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | export { default as asyncHandler } from "./src/asyncErrorHandler"; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-async-handler", 3 | "version": "0.0.1", 4 | "description": "Async Error Handling Middleware for Express with ESM support.", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "build": "vitest --no-watch && tsc", 9 | "test": "vitest --no-watch", 10 | "test:dev": "vitest --watch", 11 | "test:coverage": "vitest run --coverage", 12 | "prepare": "husky install" 13 | }, 14 | "keywords": [ 15 | "async", 16 | "error", 17 | "handler", 18 | "express", 19 | "express-async-handler", 20 | "express-async-errors", 21 | "express-async-error-handler", 22 | "http", 23 | "error-handler" 24 | ], 25 | "private": false, 26 | "author": "MURANGWA Pacifique", 27 | "license": "MIT", 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/pacifiquem/node-async-handler.git" 31 | }, 32 | "bugs": { 33 | "url": "https://github.com/pacifiquem/node-async-handler/issues" 34 | }, 35 | "devDependencies": { 36 | "@types/express": "^4.17.21", 37 | "@types/node": "^16.11.9", 38 | "express": "^4.18.2", 39 | "husky": "^8.0.3", 40 | "typescript": "^4.5.4", 41 | "vitest": "^1.1.1" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/asyncErrorHandler.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | 3 | interface AsyncHandlerOptions { 4 | logError?: boolean; 5 | } 6 | 7 | function asyncHandler(fn: Function, options: AsyncHandlerOptions = {}) { 8 | return function asyncHandlerWrapper(req: Request, res: Response, next: NextFunction) { 9 | return Promise.resolve(fn(req, res, next)).catch((error) => { 10 | if (options.logError) { 11 | console.error('Error:', error); 12 | } 13 | next(error); 14 | }); 15 | }; 16 | } 17 | 18 | export default asyncHandler; -------------------------------------------------------------------------------- /test/asyncErrorHandler.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, it, expect } from 'vitest'; 2 | import asyncHandler from '../src/asyncErrorHandler'; 3 | 4 | describe('asyncHandler', () => { 5 | 6 | it('should catch exceptions of a function passed into it', async () => { 7 | const error = new Error('catch me!') 8 | const foo = asyncHandler(() => { 9 | throw error 10 | }); 11 | expect(foo).to.throw(error) 12 | }); 13 | 14 | }); 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "moduleResolution":"NodeNext", 5 | "module": "NodeNext", 6 | "outDir": "./dist", 7 | "esModuleInterop": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "strict": true, 10 | "skipLibCheck": true, 11 | "declaration": true 12 | } 13 | } --------------------------------------------------------------------------------