首页 > 解决方案 > 强制 javascript 开发人员处理异常

问题描述

为了描述函数抛出异常的可能性,我们可以使用 JSDock

/**
 * @throws {Error}
 */
export const a = () => {
  throw new Error("i am exist only to throw exceptions...")
}

好吧,这很可爱。但是开发人员可能会错过该描述,并且不会将函数包装在 try...catch 中。

我如何强制 typescript / IDE / ES-lint 告诉我我忘记在 try...catch 中包装函数?

我应该考虑制作一个 ES-lint 插件的想法吗?或者有没有现成的解决方案?(除了带有所有可能参数的自动测试)

谢谢!

标签: javascripttypescripttry-catcheslint

解决方案


try...catch是情境性的——如果你只想在 JSDoc 中记录一个异常和/或自己不能立即处理它(例如严重错误),你会遇到当前方法的麻烦。

此外,理想情况下,错误是自我记录的,并在代码本身中强制执行某种行为——其他一切都不是 DRY。代码/注释可能会不同步,您不妨忘记记录@throws {Error}.

所以我不确定IDE或ES-lint插件是否是个好主意。相反,您可以创建某种Either数据类型,强制所有可能抛出函数 ( a) 的消费者在某个时候对错误做出反应——否则他们不会得到返回值。一个简化的例子:

// wrap a riscy throwing function, so that it returns a plain value ("purify it")
const tryCatch = (myRiskyFn) => {
  try {
    return { val: myRiskyFn() };
  } catch (e) {
    return { err: e };
  }
}

// enforce client to handle error branch here, so we can return a well defined value back.
const valueFromEither = (either, onError) =>
  "err" in either ? onError(either.err) : either.val;

// Test error case:
const a = () => { throw new Error("some error..."); };
const either1 = tryCatch(a); // throws internally
const result1 = valueFromEither(either1, err => `Oh my! ${err}`);
console.log(result1); // Oh my! Error: some error...

// Test success case:
const b = () => 42;
const either2 = tryCatch(b); // goes thru
const result2 = valueFromEither(either2, err => `Oh my! ${err}`);
console.log(`yay! ${result2}`); // yay! 42

(以IO, Either,TaskEither函数式编程方法的风格,但您可以自己使用它!)


推荐阅读