Get the location information of PromiseRejectionEvent
P粉447785031
P粉447785031 2024-02-17 18:06:26
0
1
447

I have some code where async functions may throw errors and I'm using unhandledrejection events to handle them because those uncaught throw don't error events are fired because they occur within a Promise. So my error handler is getting PromiseRejectionEvent instead of ErrorEvent.

So far so good, error handling is working fine.

But I have a small problem here, that is, the PromiseRejectionEvent event lacks location information, unlike the ErrorEvent event, which puts the location into the code that raised the error Lieutenant General is very useful.

When the code does not use the async function and the handler gets the ErrorEvent event, event.filename, event.lineno## is required. # and event.colno, but these cphpcn activities are missing from PromiseRejectionEventphpcnend.

SO My question is: Is there any way I can wrap the PromiseRejectionEvent and re-dispatch it so that in the end I have an ErrorEvent with location information ?

I tried something like this:

bigFunctionWithAllTheCodeIncludingAsyncFunctions()
.catch(error => {
    const errorEvent = new ErrorEvent('unhandledrejection', {
            'error': error,
    });
    window.dispatchEvent(errorEvent);
});

The above code generates a correct

ErrorEvent and related error message but all position information is useless (0 represents row and column, '' represents the file name).

BTW, I've checked to get the stack trace in the unhandledrejection event handler, but currently I can't wrap the Promise in my code using a custom class.

Thank you very much in advance :)

P粉447785031
P粉447785031

reply all(1)
P粉835428659

Yes! But it cannot be achieved by building and dispatching ErrorEvent yourself. Instead, you can use reportError:

window.onunhandledrejection = event => {
  reportError(event.reason);
};

window.onerror = (...args) => {
  console.log('onerror', args);
};

(async function() { throw new Error("oops"); }());
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!