Six Colors
Six Colors

This Week's Sponsor

Magic Lasso Adblock: YouTube ad blocker for Safari


By Jason Snell

Bad AppleScript: Try, try again

Note: This story has not been updated since 2020.

I use a lot of different automation tools to get my job done more productively. But software grows and changes and sometimes that means things break.

I’ve been using Photoshop for more than 25 years(!) and I pay $99 per year for the privilege of using the latest and greatest version. But the recent update to Photoshop CC 2017 caused the scripts I use (via an Automator action) to automatically resize, save, and upload all the image files on Six Colors to stop working.

The bug Adobe introduced was a peculiar one. Scripts only broke on their first attempt to launch and use Photoshop. After a lot of guessing, I pinpointed the problem, which is that Photoshop was declaring itself ready to accept scripting commands before it was able to do anything with them. During this fragile and temporary state, if my script tried to tell Photoshop to open a file, it would reply with an error and my script would fail.

I considered inserting delays—any AppleScript person will tell you that sometimes telling the script to wait a couple of seconds can be the difference between success and failure—but when Photoshop was already up and running, the delays weren’t necessary. I made a version that checked to see if Photoshop was up and running, and if it wasn’t, then insert a long delay. Still, the results were not reliable—I still got error messages sometimes.

One day I realized that the error was the problem. If I could tell my script to respond to that error with some different behavior, I could get it to work. Fortunately, AppleScript has this error-handling facility courtesy of its try statement. So here’s what I wrote:

    tell application "Adobe Photoshop CC 2017"
        try
            open file (POSIX path of fileAlias)
        on error
            tell me to delay 5
            activate
            open file (POSIX path of fileAlias)
        end try

In other words, the script opens a file in Photoshop, but if it receives an error message—which it shouldn’t, unless it’s hit this bug—it waits five seconds, brings Photoshop to the foreground, and tries again.

Kind of a ridiculous workaround—but you know what? The script has returned to 100 percent reliability.

If you appreciate articles like this one, support us by becoming a Six Colors subscriber. Subscribers get access to an exclusive podcast, members-only stories, and a special community.


Search Six Colors