Passing an application command to a subroutine

Hello Applescript Gurus! :smiley:

I’m having some trouble with the following code and was hoping somebody more knowledgeable can help me out. As a bit of background, I’ve been receiving intermittent -609 (Invalid Connection) errors when using “tell application x to y”. Specifically, this occurs when the command is sent to an application that has recently crashed or quit; my script will encounter this situation from time to time (it’s job is to monitor the running applications and restart them if necessary), so I require a method of handling the -609’s and moving on.

Rather than surrounding every tell statement with a try … end try block, I’d prefer a wrapper for the tell command so I can just call tell_wrapper() when I need the safe-fail behaviour. I’ve included some example code below, but it’s not working as expected – rather than opening a new document in TextEdit, it opens a new document in ScriptEditor.


property editor : application "TextEdit"

on write_log(msg)
	-- write msg to logfile
end write_log

on tell_wrapper(app_reference, cmd)
	try
		tell app_reference to cmd
	on error errMsg number errNum
		write_log(errMsg & "(" & errNum & ")" & return)
	end try
end tell_wrapper

tell_wrapper(editor, make new document)

-- note: quoting doesn't work either, e.g.
-- tell_wrapper(editor, "make new document")

Is it possible to pass an application command as a parameter to the tell_wrapper() subroutine as I’m attempting to do here?

Your help is greatly appreciated.

Hi,

second-level evaluation is a bit tricky,
you can use this:

property editor : "TextEdit"

on write_log(msg)
	-- write msg to logfile
end write_log

on tell_wrapper(app_reference, cmd)
	try
		tell application app_reference
			run script cmd
		end tell
	on error errMsg number errNum
		write_log(errMsg & "(" & errNum & ")" & return)
	end try
end tell_wrapper

tell_wrapper(editor, "make new document")

Worked like a charm, StefanK. Thank you!