I’ve created a Shortcut for MacOS that incorporates Applescript to navigate the UI of System Settings. In a few places throughout where I need to wait for a UI element to load, I run a version of:
repeat until UI element 1 exists
delay 0
end repeat
Most of the time this works fine, and the Shortcut completes running without a problem. Occasionally though, the UI takes longer than usual to load (I’m navigating into the iCloud+ Hide My Email service submenu, which seems to load from a database online and the length of time to do this varies) and the Shortcut aborts and throws an error: System Events got an error: AppleEvent handler failed. Is there an alternative method, without adding unnecessary length to the delay, to achieve a delay that can handle an unknown / indefinite length?
In your post on StackOverflow you mention that it fails if doesn’t have access to iCloud, which would seem to indicate that the UI element hierarchy changes. I don’t have any “Hide My eMail” settings to test the workflow, but does running the script in Script Editor/Debugger provide more clues?
If you can determine what changes in the UI on that error, you can check for it and gracefully exit. Or you can just enclose the whole thing in a try statement and put up an alert if anything fails. Same result, but maybe with a message that is not as mysterious.