跳到主要內容

only-throw-error

禁止將非 Error 值拋出為例外情況。

🔒

擴充套件 "plugin:@typescript-eslint/strict-type-checked" in an ESLint 設定檔 即可啟用此規則。

💭

此規則需要 類型資訊 才能執行。

良好做法一向是僅 throw Error 本物件或使用 Error 物件作為自訂例外情況的基底物件。 Error 物件的基本好處在於能自動追蹤其建立及來源位置。

此規則限制能拋出為例外情況的項目。

no-throw-literal 移轉

此規則以前稱為 no-throw-literal。我們鼓勵使用者改用新名稱 only-throw-error,因為舊名稱會在 typescript-eslint 的未來主要版本中移除。

新名稱具有完全相同的實作,可直接替換舊名稱。

範例

此規則旨在於拋出例外時保持一致性,不允許拋出字面值和其他不可能是 Error 物件的運算式。

throw 'error';

throw 0;

throw undefined;

throw null;

const err = new Error();
throw 'an ' + err;

const err = new Error();
throw `${err}`;

const err = '';
throw err;

function getError() {
return '';
}
throw getError();

const foo = {
bar: '',
};
throw foo.bar;
在遊樂場中開啟

如何使用

.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-throw-literal": "off",
"@typescript-eslint/only-throw-error": "error"
}
};

在遊樂場中嘗試此規則 ↗

選項

請參閱 eslint/no-throw-literal 選項

此規則增加了下列選項

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,
};

何時不使用

類型檢查的 linter 規則比傳統的 linter 規則更強大,但也需要設定 類型檢查的 linting。如果您在啟用類型檢查的規則後遇到效能下降的情況,請參閱 效能疑難排解

資源

取自 ESLint core,❤️ 奉獻。