【问题标题】:try catch not always works in iced coffee scripttry catch 并不总是适用于冰咖啡脚本
【发布时间】:2014-01-10 23:12:38
【问题描述】:

我在iced coffee script 中使用try catch 块。我调用不存在对象a 的不存在方法fake 并期望捕获错误。

db = require '../../call/db.iced'
try
    await db.find "79", defer c, d
    a.fake()
catch error
    console.log "error catched"
    console.log error

但是在调用函数db.find a.fake() 在控制台中抛出错误之后,它并没有按预期使用try catch 块。

如果我注释掉字符串await db.find "79", defer c, d...

db = require '../../call/db.iced'
    try
        # await db.find "79", defer c, d ############## commented out
        a.fake()
    catch error
        console.log "error catched"
        console.log error

...它按预期工作并捕获了错误。

我尝试通过其他简单的异步函数调用来更改字符串await db.find "79", defer c, d,但它们工作正常并且错误被很好地捕获。

有趣的是,函数db.find 运行良好。当我注释掉字符串a.fake()...

db = require '../../call/db.iced'
    try
        await db.find "79", defer c, d
        #a.fake() ################################ commented out
    catch error
        console.log "error catched"
        console.log error

...这个脚本没有任何错误,因此不会捕获错误。

无法弄清楚为什么我在函数await db.find "79", defer c, d 之后无法捕获错误。

【问题讨论】:

    标签: error-handling iced-coffeescript


    【解决方案1】:

    The documentation statestry catch 声明如下:

    唯一的例外是try,它在调用时不会捕获异常 从事件处理程序主循环,出于同样的原因,手动滚动 异步代码和try 不能很好地协同工作。

    我怀疑由于 db.find 是异步调用的,try 构造保留在 db.find 线程中,并且不会保留在主线程中。这将导致您描述的结果。

    一种粗略的解决方案是同时捕获两个函数调用。但是,我认为使用await 的正确方法是使用defer 函数。 Check out the documentation for an explanation.

    此外,您可能会发现以下内容很有帮助:

    可能的解决方案

    1. 在这两个语句周围放置一个 try catch。

      try
          await db.find "79", defer c, d
      catch error
          console.log "error catched"
          console.log error
      try
          a.fake()
      catch error
          console.log "error catched"
          console.log error
      
    2. As described in the link above,将db.find 放在try catch 之外,并以另一种方式检测它的错误。

      await db.find "79", defer err, id
      if err then return cb err, null
      
      try
          a.fake()
      catch error
          console.log "error catched"
          console.log error
      

    【讨论】:

    • 谢谢!我应该如何更改 try catch 块以捕获 a.fake() 调用上的错误?或者唯一的方法是从 try 块中排除异步函数?
    • 为我的回答添加了一些解决方案。看看有没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2012-05-04
    • 2013-09-12
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多