热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在承诺中捕捉未被发现的异常-HowtocatchuncaughtexceptioninPromise

IsthereanywaytogloballycatchallexceptionsincludingPromiseexceptions.Example:是否有办法全局捕获所有

Is there any way to globally catch all exceptions including Promise exceptions. Example:

是否有办法全局捕获所有异常,包括承诺异常。例子:

    window.Onerror= function myErrorHandler(errorMsg, url, lineNumber) {
        alert("Error occured: " + errorMsg);//or any message
        return false;
    }

    var myClass = function(){

    }


    var pr = new Promise(function(resolve, react){
        var myInstance = new myClass();
        myInstance.undefinedFunction(); // this will throw Exception
        resolve(myInstance);
    });


    pr.then(function(result){
        console.log(result);
    });

    // i know right will be this:
    // pr.then(function(result){
    //     console.log(result);
    // }).catch(function(e){
    //     console.log(e);
    // });

This script will silently die without error. Nothing in firebug.

这个脚本将无声地死去,不会出错。firebug。

My question is if I do a mistake and forgot to catch it is there any way to catch it globally?

我的问题是,如果我犯了一个错误,却忘了抓住它,有没有办法在全球范围内抓住它?

5 个解决方案

#1


18  

Update, native promises now do the following in most browsers:

更新,本地承诺现在在大多数浏览器做以下事情:

window.addEventListener("unhandledrejection", function(err, promise) { 
    // handle error here, for example log   
});

We were just discussing this the other day.

前几天我们刚刚讨论过这个问题。

Here is how you'd do this with bluebird:

这是你如何对付蓝鸟的方法:

window.Onpossiblyunhandledexception= function(){
    window.onerror.apply(this, arguments); // call
}

window.Onerror= function(err){
    console.log(err); // logs all errors
}

With Bluebird it's also possible to use Promise.onPossiblyUnhandledRejection. The calls for done are not needed as the library will detect unhandled rejection itself unlike Q (UPDATE 2016 - I now wrote code for Q and it does this).

对于蓝鸟来说,也可以使用promi .on表示不可能完成的任务。不需要调用done,因为库将检测未处理的拒绝本身,不像Q(更新2016 -我现在为Q编写代码,它这样做)。

As for native promises - they will eventually report to either window.onerror or a new handler but the specification process is not yet done - you can follow it here.

至于本地承诺——它们最终将向任一窗口报告。onerror或新的处理程序,但是规范过程还没有完成——您可以在这里跟踪它。

#2


15  

Most promise implementations don't currently provide the type of functionality you are referring to, but a number of 3rd-party promise libraries (including Q and bluebird) provide a done() method that will catch and rethrow any uncaught errors, thus outputting them to the console.

大多数承诺实现目前不提供您正在引用的功能类型,但是许多第三方承诺库(包括Q和bluebird)提供了一个done()方法,可以捕获和重新抛出未捕获的错误,从而将它们输出到控制台。

(Edit: see Benjamin Gruenbaum's answer about Bluebird's features for handling uncaught exceptions)

(编辑:参见本杰明·格伦鲍姆(Benjamin Gruenbaum)关于知更鸟处理未捕获异常的特性的回答)

So if you have that, you'd just need to follow the rule of thumb that any promise you use should either be returned or terminated with .done():

因此,如果你有这样的经验,你只需要遵循经验法则,你使用的任何承诺都应该被退回或终止。

pr.then(function(result){
    console.log(result);
})
.done();

To quote from the Q API reference:

引用Q API参考:

The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. Terminating with catch is not sufficient because the catch handler may itself throw an error.

“完成”和“使用”的黄金法则是:要么把你的承诺归还给别人,要么,如果链终止于你,你就可以终止它。使用catch终止是不够的,因为catch处理程序本身可能抛出错误。

I realize that this still requires a bit of extra work and you can still forget to do this, but it is an improvement over having to .catch() and explicitly handle every error, especially for the reason pointed out above.

我意识到这仍然需要一些额外的工作,您仍然可以忘记这样做,但是这比必须要.catch()并显式地处理每个错误要好,特别是由于上面提到的原因。

#3


4  

In Node.js, you can use:

在节点。js,您可以使用:

process.on('unhandledRejection', (reason, promise) => {
  console.error(`Uncaught error in`, promise);
});

#4


2  

If you're writing code that can be executed both in a browser & in a Node.js environment, you could wrap your code in a self-executing function like this :

如果您正在编写可以在浏览器和节点中执行的代码。js环境下,可以将代码封装在一个自执行函数中,如下所示:

var isNode = (typeof process !== 'undefined' && typeof process.on !== 'undefined');
(function(on, unhandledRejection) {
    // PUT ANY CODE HERE
    on(unhandledRejection, function(error, promise) {
        console.error(`Uncaught error in`, promise);
    });
    // PUT ANY CODE HERE
})(
    isNode ? process.on.bind(process) : window.addEventListener.bind(window),
    isNode ? "unhandledRejection" : "unhandledrejection"
);

What would happen if you use this code :

如果您使用此代码会发生什么:

  • If you'd run it in a Node.js environment, your handler would be attached to the process object and be executed when you have an uncaught exception in a promise.

    如果你在一个节点上运行它。在js环境中,您的处理程序将被附加到流程对象,并在承诺中出现未捕获异常时执行。

  • If you'd run it in a browser environment, your handler would be attached to the window object and be executed when you have an uncaught exception in a promise and your browser supports the unhandledrejection event.

    如果您在浏览器环境中运行它,您的处理程序将被附加到窗口对象,当您在一个承诺中有一个未被捕获的异常并且您的浏览器支持unhandledrejection事件时将被执行。

  • If you'd run it in a browser environment without support for the unhandledrejection, you will not be able to catch your uncaught exception and your unhandledrejection event handler will never be triggered, but you would not get any errors if there's no uncaught exceptions.

    如果您在不支持unhandledrejection的浏览器环境中运行它,您将无法捕获未捕获的异常,也不会触发unhandledrejection事件处理程序,但是如果没有未捕获的异常,您将不会得到任何错误。

#5


0  

If you are using native Promise, it's pretty simple.
You only need to .catch this reject some where.

如果你使用的是原生承诺,这很简单。你只需要。抓住这个拒绝的地方。

ajax(request).catch(function(rejected){
      console.log(rejected);
});

If I don't catch it somewhere, the uncaught in promise will keep showing. But If I catch it somewhere...

如果我没有在某个地方发现它,未被发现的承诺将继续显现。但是如果我在什么地方抓到它……


推荐阅读
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 本文探讨了C语言中指针的应用与价值,指针在C语言中具有灵活性和可变性,通过指针可以操作系统内存和控制外部I/O端口。文章介绍了指针变量和指针的指向变量的含义和用法,以及判断变量数据类型和指向变量或成员变量的类型的方法。还讨论了指针访问数组元素和下标法数组元素的等价关系,以及指针作为函数参数可以改变主调函数变量的值的特点。此外,文章还提到了指针在动态存储分配、链表创建和相关操作中的应用,以及类成员指针与外部变量的区分方法。通过本文的阐述,读者可以更好地理解和应用C语言中的指针。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了PE文件结构中的导出表的解析方法,包括获取区段头表、遍历查找所在的区段等步骤。通过该方法可以准确地解析PE文件中的导出表信息。 ... [详细]
author-avatar
我想去海边6_414
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有