javascript - 在 VS Code 中调试时从 Promise 中的拒绝中获取未处理的异常

标签 javascript debugging typescript promise visual-studio-code

在 VS Code 中调试时,我在 Promise 中收到来自 reject(new SomeKindOfError()) 的未处理异常错误,但在我不进行调试时却没有,这正常吗?还是我的代码结构有问题?

根据我从有关 Promise 和 stackoverflow 答案的几个教程中了解到的内容,Promise 链末尾的 Promise#catch() 足以捕获链中可能发生的拒绝。但为什么它仍然被调试器标记为未处理的异常?

这是我使用的结构:

function returnAPromise(): Promise<any> {
    return new Promise<any>((resolve, reject) => {
        // do something here
        if (isConditionMet) {
            resolve()
        } else {
            reject(new SomeKindOfError()) // debugger breaks here
        }
    })
}

someElement.onSomeEvent(() => {
    // only care about the errors that might occur
    returnAPromise().catch((error) => {
        if (error instanceof SomeKindOfError) {
            // perform necessary actions when this error occurred
        }
    })
})

附注我已经尝试过在遇到未处理的异常时在不执行中断的情况下进行调试,但这有点违背了使用调试器的目的:检查可能发生的未处理的异常。

编辑:

Unhandled exception error from a reject

此外,我尝试在没有捕获的情况下调用 returnAPromise() ,并且在调试器控制台中打印一条警告,指出 rejected Promise not handler inside 1 Second

最佳答案

感谢 @Bergi 指出这是由于 Error 构造函数造成的。我没有注意到...:'(

事实证明,问题并不是因为 Promise 没有捕获它。这是因为扩展内置 Typescript 类时出现错误。

这是一个stackoverflow post我发现,它引用了这个Typescript documentation关于 v2.1 中的重大更改。

Extending built-ins like Error, Array, and Map may no longer work. As part of substituting the value of this with the value returned by a super(...) call, subclassing Error, Array, and others may no longer work as expected. This is due to the fact that constructor functions for Error, Array, and the like use ECMAScript 6's new.target to adjust the prototype chain; however, there is no way to ensure a value for new.target when invoking a constructor in ECMAScript 5. Other downlevel compilers generally have the same limitation by default.

因此,我必须在扩展 Error 类的类的构造函数中添加一行额外的代码。

class SomeKindOfError extends Error {
    constructor(m: string) {
        super(m)

        // I have to add this additional line of code
        Object.setPrototypeOf(this, SomeKindOfError.prototype)
    }
}

关于javascript - 在 VS Code 中调试时从 Promise 中的拒绝中获取未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264724/

相关文章:

c++ - _Block_Type_Is_Valid (pHead->nBlockUse) 错误

java - Eclipse 错误调试

node.js - 如果路径以 "./"和 nocase : true - bug or expected? 开头,则 Node glob 不匹配任何内容

node.js - 如何像我们做扩展一样在VSCODE上发布LSP语言服务器

javascript - 如何映射对象数组并将它们作为按 "categories"排序的新对象数组返回

javascript - 使用 CefGlue/CE​​F3 从 JavaScript 调用 .NET

javascript - 这段 SHA-256 Javascript 代码有什么问题?

javascript - 如何从 UL LI 元素正确提交表单?

javascript - 将图像 URL 发送到特定文本字段的 Google Chrome 扩展程序

javascript - 如何使用 Excel Javascript Addins 计算所有非空白单元格?