How to catch uncaught exception in Promise

后端 未结 5 1521
悲哀的现实
悲哀的现实 2020-12-04 17:22

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

    window.onerror = function myErrorHandler(errorMsg, url, lineNumb         


        
5条回答
  •  心在旅途
    2020-12-04 18:02

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

    window.addEventListener("unhandledrejection", function(promiseRejectionEvent) { 
        // 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).

    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.

提交回复
热议问题