2013-12-22 32 views
5

我使用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 

但在控制台调用函数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由其他简单的异步函数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 

...这个剧本工作没有任何错误,所以没有捕捉错误。

找不到功能await db.find "79", defer c, d后为什么我不能捕获错误。

回答

1

The documentation states以下的try catch声明:

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

我怀疑,既然db.find异步调用,该try结构仍然与db.find线程,并且不留在主线程。这会导致你描述的结果。

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

此外,您可能会发现以下帮助:

可能的解决方案

  1. 广场两个语句围绕一个尝试捕捉。

    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的尝试捕捉外,并检测它是错误的另一种方式。

    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 
    
+0

谢谢!我应该如何改变try catch块来捕获'a.fake()'调用的错误?或者,单一的方法是从'try'块中排除异步函数? –

+0

为我的答案增加了一些解决方案。看看是否有帮助。 – JSuar