prefer-promise-reject-errors
Require using Error objects as Promise rejection reasons.
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.
This rule extends the base prefer-promise-reject-errors
rule from ESLint core. 它使用类型信息来强制 Promise
仅被 Error
对象拒绝。
¥It uses type information to enforce that Promise
s are only rejected with Error
objects.
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
Promise.reject('error');
const err = new Error();
Promise.reject('an ' + err);
new Promise((resolve, reject) => reject('error'));
new Promise((resolve, reject) => {
const err = new Error();
reject('an ' + err);
});
Open in PlaygroundPromise.reject(new Error());
class CustomError extends Error {
// ...
}
Promise.reject(new CustomError());
new Promise((resolve, reject) => reject(new Error()));
new Promise((resolve, reject) => {
class CustomError extends Error {
// ...
}
return reject(new CustomError());
});
Open in Playground如何使用
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"prefer-promise-reject-errors": "off",
"@typescript-eslint/prefer-promise-reject-errors": "error"
}
});
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"prefer-promise-reject-errors": "off",
"@typescript-eslint/prefer-promise-reject-errors": "error"
}
};
在线运行试试这个规则 ↗
选项
See eslint/prefer-promise-reject-errors
's options.
¥Options
该规则添加了以下选项:
¥This rule adds the following options:
interface Options {
/**
* Whether to always allow throwing values typed as `any`.
*/
allowThrowingAny?: boolean;
/**
* Whether to always allow throwing values typed as `unknown`.
*/
allowThrowingUnknown?: boolean;
}
const defaultOptions: Options = {
allowThrowingAny: false,
allowThrowingUnknown: false,
};
何时不使用它
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.
'## 资源'
Taken with ❤️ from ESLint core.