eslint-plugin-safeguard
Version:
A custom ESLint plugin that provides multiple rules to enforce best practices and code safety.
81 lines (58 loc) • 1.81 kB
Markdown
This is an ESLint rule that ensures `await` expressions are inside `try-catch` blocks, helping to prevent unhandled promise rejections and improve code robustness.
- Detects `await` expressions that are not inside a `try-catch` block.
- Reports an error if an `await` is used without proper error handling.
- Helps enforce best practices for asynchronous error handling.
1. Install the plugin using `pnpm`, `npm`, or `yarn`:
```sh
pnpm add -D eslint-plugin-safeguard
npm install --save-dev eslint-plugin-safeguard
yarn add -D eslint-plugin-safeguard
```
2. Add the rule to your ESLint configuration(eslint.config.js):
```js
import safeguard from 'eslint-plugin-safeguard';
```
```js
{
plugins: {
safeguard,
},
"rules": {
"safeguard/trycatch-ensurer": "error"
}
}
```
This rule enforces that all `await` expressions are inside a `try-catch` block.
```js
async function fetchData() {
const data = await fetch('https://api.example.com');
return data.json();
}
```
```js
async function fetchData() {
try {
const data = await fetch('https://api.example.com');
return data.json();
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}
```
- The rule checks if an `await` expression appears inside a `try` block.
- If no `try-catch` block is found, ESLint will report an error.
- If a `try` block is found **but lacks a `catch` handler**, the rule will also trigger a warning.
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
---
**Author:** Estarlin R ([estarlincito.com](https://estarlincito.com))