gpt4 book ai didi

error-handling - try catch 并不总是适用于冰 CoffeeScript

转载 作者:行者123 更新时间:2023-12-03 22:42:38 24 4
gpt4 key购买 nike

我用 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通过其他简单的异步函数调用,但它们工作正常并且错误被很好地捕获。

有趣的是函数 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 后无法捕获错误.

最佳答案

The documentation states以下在 try catch声明:

The only exception is try, which doesn't catch exceptions when called from event handlers the main loop, for the same reason hand-rolled asynchronous code and try do not work well together.



我怀疑是因为 db.find被异步调用, try构造保留在 db.find 中线程并且不停留在主线程中。这将导致您描述的发现。

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

此外,您可能会发现以下内容有帮助:
  • How to correctly handle errors with IcedCoffeeScript?

  • 可能的解决方案
  • 在这两个语句周围放置一个 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
  • 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
  • 关于error-handling - try catch 并不总是适用于冰 CoffeeScript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20731598/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com