javascript - 强制 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 插件的想法吗?或者有没有现成的解决方案?(除了带有所有可能参数的自动测试)
谢谢!
解决方案
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
函数式编程方法的风格,但您可以自己使用它!)
推荐阅读
- spring-boot - 即使单元测试成功,Maven 构建也会失败
- angular - 在 angular.json 文件中设置 optimization=true 时无法下载文件
- json - 从 JSON 响应中删除 EclipseLink 特定字段
- c - 将字符串从 Rust 传递到 C 会导致段错误或错误
- python - 如何修复打印在带有随机库的 python 中不起作用
- ansible - 使用 Google-Authenticator 时的 Ansible SSH 连接
- mysql - 将 SQL 连接查询转换为 django ORM
- php - 如何在 PHP 变量中添加值作为源代码
- angular - ng8 升级:错误:未知的 android 版本 67
- redis - redis设置中的数值数据库值有什么作用?