How to catch uncaught exception in Promise

后端 未结 5 1517
悲哀的现实
悲哀的现实 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 17:46

    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 :

    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.

    • 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.

    • 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.

提交回复
热议问题