In Applescript, how to get a line number or stack trace on error

applescripterror

I'm writing some fairly complex Applescripts, but when something goes wrong – Apple event timed out – or similar, I can't tell precisely where it failed.

At the moment, I'm wrapping all handlers with try blocks, with an on error that re-raises the error, with a reference to the handler name and the value of a variable that I set at various points through the handler so I can isolate the error to somewhere between two points.

** Is there a way to get Applescript to say 'Apple event timed out at line 15 in await(), at line 60 in connectRemoteUser(), at line 90 in autostartTestUsers()' without having to code it all directly?

I can't rely on the script editor's location highlighting because the errors happen intermittently when the script is out in production.

Best Answer

It's ugly but it works...

try
    set marker to 1
    -- do stuff
    set marker to 2
    -- do stuff
    set marker to 3
    1 / 0
    set marker to 4
on error errMsg number errNum
    tell application "SystemUIServer"
        display alert (marker & space & errMsg & return & return & "Error number " & errNum as text) buttons "Cancel" cancel button "Cancel"
    end tell
end try