尝试捕获并不总是在冰咖啡脚本中工作

Max*_*mov 5 error-handling iced-coffeescript

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

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

但是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
Run Code Online (Sandbox Code Playgroud)

...它按预期工作,并且错误被捕获.

我尝试await db.find "79", defer c, d通过其他简单的异步函数calles 更改字符串,但它们工作正常,错误很好.

有趣的是功能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
Run Code Online (Sandbox Code Playgroud)

...这个脚本没有任何错误,所以没有捕获错误.

无法弄清楚为什么我不能在功能后发现错误await db.find "79", defer c, d.

JSu*_*uar 1

该文档在声明中声明了以下内容try catch

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

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

一种粗略的解决方案是捕获这两个函数调用。不过,我认为正确的使用方法await是使用函数defer查看文档以获取解释。

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

可能的解决方案

  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
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如上面的链接所述,放置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
    
    Run Code Online (Sandbox Code Playgroud)