promise/catch-or-return 限制
它的作用
确保每次对一个 Promise 调用 then() 时,也必须调用 catch()。例外情况是来自函数的返回的 Promise。
为什么这是不好的?
在 Promise 中未捕获错误可能导致难以调试的问题,或遗漏错误条件的处理。最坏情况下,未处理的 Promise 拒绝可能导致应用程序崩溃。
示例
此规则的 错误 代码示例:
javascript
myPromise.then(doSomething);
myPromise.then(doSomething, catchErrors); // catch() 可能稍好一些此规则的 正确 代码示例:
javascript
myPromise.then(doSomething).catch(errors);
function doSomethingElse() {
return myPromise.then(doSomething);
}
const arrowFunc = () => myPromise.then(doSomething);配置
此规则接受一个配置对象,包含以下属性:
allowFinally
type: boolean
default: false
是否允许将 finally() 作为终止方法。
allowThen
type: boolean
default: false
是否允许使用两个参数的 then() 作为终止方法。
terminationMethod
type: string[]
default: ["catch"]
允许的终止方法列表(例如:catch、done)。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["promise"],
"rules": {
"promise/catch-or-return": "error"
}
}bash
oxlint --deny promise/catch-or-return --promise-plugin