eslint-plugin-safeguard
Version:
A custom ESLint plugin that provides multiple rules to enforce best practices and code safety.
89 lines (63 loc) • 2.02 kB
Markdown
This is an ESLint rule that ensures `Error` and `error` constructors are not used directly, enforcing the use of custom error classes for better error handling and debugging.
- Detects usage of `new Error()` and `new error()`.
- Reports an error when `throw new Error()` or `throw new error()` is used.
- Enforces the use of structured custom error classes like `AppError`.
- Helps enforce best practices for structured 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/no-raw-error": "error"
}
}
```
This rule enforces that `Error` or `error` constructors are not used directly. Instead, users must define and use a custom error class.
```js
throw new Error('Something went wrong');
const err = new error('This should not be used');
```
```js
class AppError extends Error {
constructor(
message: string,
public code?: string,
) {
super(message);
this.name = 'AppError';
}
}
const handleError = (message: string, code?: string): never => {
throw new AppError(message, code);
};
export default handleError;
//Usage
handleError('Something went wrong', 'SOME_ERROR_CODE');
```
- The rule checks for `new Error()` and `new error()` usage.
- If found, ESLint will report an error.
- Encourages using `AppError` or other structured custom error classes for more descriptive error handling.
This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
---
**Author:** Estarlin R ([estarlincito.com](https://estarlincito.com))