Search code examples
applescriptitunes

How can I check for existence of Itunes track in Applescript without throwing error


the idea of this script (simplified to show the issue) is checks if a track exists,

    tell application "iTunes"
        set matchtrack to get first track in playlist 1 whose persistent ID is "F1A68AD90AA66648"
        if matchtrack is not {} then
            print name of matchtrack
        else
            print "no track found"
        end if
    end tell

unfortunately if the track does not exist it gives error

"iTunes got an error: Can’t get track 1 of playlist 1 whose persistent ID = \"F1A68AD90AA66648\"." number -1728 from track 1 of playlist 1 whose persistent ID = "F1A68AD90AA66648"
'

instead of just printing 'no track found'


Solution

  • get first track give a track object or an error

    tracks give a list of one track or an empty list

    tell application "iTunes"
        set matchtrack to tracks in playlist 1 whose persistent ID is "F1A68AD90AA66648"
        if matchtrack is not {} then
            return name of item 1 of matchtrack
        else
            return "no track found"
        end if
    end tell