typescript/only-throw-error 严谨
它的作用
此规则禁止抛出非错误对象的值。
为什么这是不好的?
按照最佳实践,应仅抛出 Error 对象(或其子类)。这是因为 Error 对象会自动捕获堆栈跟踪信息,这对调试非常有用。此外,某些工具和运行环境期望被抛出的值是 Error 对象。
示例
以下为 错误 的代码示例:
ts
throw "error"; // 抛出字符串
throw 42; // 抛出数字
throw true; // 抛出布尔值
throw { message: "error" }; // 抛出普通对象
throw null; // 抛出 null
throw undefined; // 抛出 undefined
const error = "Something went wrong";
throw error; // 抛出非 Error 变量以下为 正确 的代码示例:
ts
throw new Error("Something went wrong");
throw new TypeError("Invalid type");
throw new RangeError("Value out of range");
// 自定义错误子类
class CustomError extends Error {
constructor(message: string) {
super(message);
this.name = "CustomError";
}
}
throw new CustomError("Custom error occurred");
// 已知是 Error 对象的变量
const error = new Error("Error message");
throw error;配置
此规则接受一个配置对象,包含以下属性:
allow
type: array
default: []
允许抛出的额外类型或值的规范列表。 使用此选项可允许抛出自定义错误类型。
allow[n]
type: string
用于匹配特定声明的类型或值规范
支持四种类型的规范:
- 字符串规范(已弃用):通过名称进行通用匹配
json
"Promise"- 文件规范:匹配本地文件中声明的类型/值
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- 库规范:匹配 TypeScript 内置库类型
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- 包规范:匹配来自 npm 包的类型/值
json
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }allowRethrowing
type: boolean
default: true
是否允许重新抛出未被识别为 Error 对象的捕获值。
allowThrowingAny
type: boolean
default: true
是否允许抛出类型为 any 的值。
allowThrowingUnknown
type: boolean
default: true
是否允许抛出类型为 unknown 的值。
如何使用
要通过配置文件或命令行启用此规则,可以使用:
json
{
"rules": {
"typescript/only-throw-error": "error"
}
}bash
oxlint --type-aware --deny typescript/only-throw-error