useThrowOnlyError
¥Summary
-
规则生效日期:
v1.8.0¥Rule available since:
v1.8.0 -
诊断类别:
lint/style/useThrowOnlyError¥Diagnostic Category:
lint/style/useThrowOnlyError -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 warning。
¥The default severity of this rule is warning.
-
来源:
¥Sources:
-
灵感来自
no-throw-literal¥Inspired from
no-throw-literal -
灵感来自
@typescript-eslint/only-throw-error¥Inspired from
@typescript-eslint/only-throw-error
-
¥How to configure
{ "linter": { "rules": { "style": { "useThrowOnlyError": "error" } } }}¥Description
禁止抛出非 Error 值。
¥Disallow throwing non-Error values.
仅抛出 Error 对象本身或使用 Error 对象作为用户定义异常的基础对象的对象被认为是一种好的做法。Error 对象的基本好处是它们会自动跟踪它们的构建和来源。
¥It is considered good practice only to throw the Error object itself or an object using the Error object
as base objects for user-defined exceptions. The fundamental benefit of Error objects is that they automatically
keep track of where they were built and originated.
¥Examples
¥Invalid
throw undefined;code-block.js:1:1 lint/style/useThrowOnlyError ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Throwing non-Error values is not allowed.
> 1 │ throw undefined;
│ ^^^^^^^^^^^^^^^^
2 │
ℹ While Javascript supports throwing any value, handling non-Error values is confusing.
throw false;code-block.js:1:1 lint/style/useThrowOnlyError ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Throwing non-Error values is not allowed.
> 1 │ throw false;
│ ^^^^^^^^^^^^
2 │
ℹ While Javascript supports throwing any value, handling non-Error values is confusing.
throw "a" + "b";code-block.js:1:1 lint/style/useThrowOnlyError ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Throwing non-Error values is not allowed.
> 1 │ throw “a” + “b”;
│ ^^^^^^^^^^^^^^^^
2 │
ℹ While Javascript supports throwing any value, handling non-Error values is confusing.
¥Valid
throw new Error();throw new TypeError('biome');class CustomError extends Error {}
throw new CustomError();¥Caveats
此规则仅涵盖可以静态知道抛出值的情况。完成 JSON 类文件的知名文件列表。一旦 Biome 支持类型推断,这将在未来得到改进。
¥This rule only covers cases where throwing the value can be known statically. Complex cases such as object and function access aren’t checked. This will be improved in the future once Biome supports type inference.
¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号