如何捕获 ReasonML 中数字解析期间引发的失败异常

How to catch the Failure exception raised during number parsing in ReasonML

我是 Reason 的新手。我想通过适当的异常处理从字符串中解析浮点数。

这个有效:

let number = try (float_of_string("1,")) {
  | _ => 0.0;
};

但我想做这样的事情:

let number = try (float_of_string("1,")) {
  | Failure(_) => 0.0;
};

不幸的是,它没有捕捉到异常。我认为这是一个 Failure 异常,因为在开发人员控制台中我看到此数据有错误:

[["Failure", -2], "float_of_string"]

我也试过为自己提出这个错误,它被正确地捕获了:

try (raise(Failure("test"))) {
  | Failure(_) => Js.log("caught")
};

编辑:

我的代码应该根据沙箱工作:example on reasonml.github.io/en/try,谢谢@Yawar。如果我从节点而不是浏览器 运行 它也有效。

该函数抛出的异常似乎与我们正在比较的异常的来源不同。可能是开发环境有问题

我已经创建了一个演示存储库 - Exception Demo

你检查过float_of_string_opt了吗?此函数的类型为 string => option(float) 如果发生错误,它将是 None

或者你可以

switch (float_of_string("1,")) {
| exception (Failure(_)) => 0.0
| x => x
};

如果后端 OCaml > 4.02(BS 已升级到 4.06,因此我认为它对您可用),则可用)

主题 react-hooks(由 bsb -init -theme react-hooks 安装)中包含的 moduleserve 存在问题。在我尝试的 运行 代码的所有其他方法中:

  • 使用 webpack
  • 构建生产包
  • 通过 webpack-dev-server
  • 提供开发代码
  • 使用网络沙箱reasonml/try, codesandbox
  • 运行 使用 node
  • 从命令行生成 .js 文件

它工作正常。

我在 BuckleScript 项目中创建了一个 issue