Posts RSS Comments RSS 48 Posts and 155 Comments till now

Trapping error codes in AppleScript

If you use AppleScript you know sometimes when you try to do things such as mount a remote volume things can go wrong. Then you get a error message with number telling (hopefully) what went wrong. But you might not want that error message to show up. Maybe if that error happens you want your script to do something. If so then you have to trap that error first.

To catch an error you need to wrap the part of your script that is doing the action in a try statement. So, if I wanted to open a file I might use something like this:

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg
end try
[/codesyntax]

The script trys to run that command and if there is a problem the error message gets put into the variable errmsg. Then we can handle that error another way, perhaps with a dialog box.

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg
display dialog errmsg buttons {“Oops”}
end try
[/codesyntax]

That works great for generic errors but what if we know the error code of a specific error, such as the file doesn’t exist ,which happens to be -1728. Then we can add the number property to our on error trap and do something specific for that error.

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg number errNum
if errNum is -1728 then
display dialog “Hey, that file doesn’t exist!” buttons {“Doh!”}
else
display dialog errmsg buttons {“Oops”}
end try
[/codesyntax]

Now we can give the user specific feedback on certain errors and just display the error message for all other errors.

Comments are closed.