1

I am trying to implement a global uncaught promise error handler for a lightning web component. The goal is to reduce the catch(error) statements for promises:

getDocumentTypes() {
    getDocumentTypes({ load: this.load })
    .then(result => {      
        LightningUtil.processMessagesAndErrors2(this, result);   
        if(result.IsOK) {
            this.documentTypes = result.Payload;  
        }
    })
    .catch(error => {
        LightningUtil.logError(this, error);
    });
}

I tried to implement an unhandledrejection event listener in an LWC:

constructor() {
    super();        
    window.addEventListener('unhandledrejection', this.myFunction);
}

But the following error occurs in the console: Uncaught (in promise) Error: Lightning Web Security: Cannot add 'unhandledrejection' event listener to Window object.

Is this a limitation of the LWC SecureWindow and is there any other way to implement a global uncaught promise error handler?

1 Answer 1

2

If you were allowed to catch any error, you might be able to catch another component's uncaught exceptions. This is a LWS (Lightning Web Security) enhancement.

In the LWS distortion viewer, it says:

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window, but may also be a Worker.

This is useful for debugging and for providing fallback error handling for unexpected situations.

The event object associated with the unhandledrejection event exposes a property called reason, which can contain sensitive information.

Distorted Behavior

Currently, Lightning Web Security doesn't support setting the onunhandledrejection event handler or adding a unhandledrejection event listener; attempting to do so throws an exception.

Interestingly, this is only a problem with LWS, as the Locker API Viewer says:

Window vs SecureWindow Compatibility

onunhandledrejection

Prototype: Window

Supported

Version 46

In other words, SecureWindow does actually support this. It is likely that LWS may end up supporting this mechanism in the long term, but I can't find any documentation that backs this up.

You should be able to, however, set a boundary component that can handle all errors. This is the errorCallback part of the LWC lifecycle. This function receives a JavaScript error object, and a stack trace as a string. You can wrap your components with a border component to handle errors in a generic manner.

1
  • 1
    Thank you for the info! I tried implementing the errorCallback in a parent component, but based on my testing it only caught synchronous errors. It seemed errors from promises still needed to be caught in the child and passed to the parent which didn't help me in getting rid of the catch(error).
    – 29espoa
    Commented Apr 16 at 18:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .