Skip to content
← Back to rules

typescript/only-throw-error 細かい

💭 This rule requires type information.

何をしますか

このルールは、非 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

特定の宣言にマッチするための型または値の指定子

次の4種類の指定子に対応しています:

  1. 文字列指定子(非推奨):名前によるユニバーサルマッチ
json
"Promise"
  1. ファイル指定子:ローカルファイルで宣言された型/値にマッチ
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }
  1. ライブラリ指定子:TypeScript組み込みライブラリ型にマッチ
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }
  1. パッケージ指定子: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 型の値を投げることを許可するかどうか。

使用方法

このルールを有効にするには、設定ファイルまたは CLI で次のように使用できます:

json
{
  "rules": {
    "typescript/only-throw-error": "error"
  }
}
bash
oxlint --type-aware --deny typescript/only-throw-error

参照