User Tools

Site Tools


action:Execute_an_AppleScript

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
action:Execute_an_AppleScript [2019/11/26 21:57]
peternlewis [Scripting]
action:Execute_an_AppleScript [2021/07/21 17:58]
JMichaelTX ADD section on error handling
Line 32: Line 32:
  
  
-AppleScripts are executed in the background via osascript. This means they are not allowed to do user interaction. You can work around this by asking the current ​applicationto ​do the user interaction for you, for example:+AppleScripts are executed in the background via osascript. This means they are not allowed to do user interaction. You can work around this by asking the current ​application to do the user interaction for you, for example:
  
 ```applescript ```applescript
Line 68: Line 68:
 set myVar to do shell script "echo $KMVAR_My_KM_Variable"​ set myVar to do shell script "echo $KMVAR_My_KM_Variable"​
 </​code>​ </​code>​
 +
 +===== Error Handling =====
 +
 +If the Applescript contains errors, a system notification will be displayed when the action is run (unless you have disabled them in System Preferences).
 +
 +If a Notifications is displayed, it can happen the error message gets cut off.
 +
 +To see the entire message, view the Keyboard Maestro Engine Log, which can be found using the Keyboard Maestro.app Editor menu _Help > Open Logs Folder_, or just open this file:
 +`~/​Library/​Logs/​Keyboard Maestro/​Engine.log` and searching for "​AppleScript"​.
 +
 +You should find a log entry like this:\\
 +  2021-07-21 16:43:53 Execute an AppleScript failed with script error:
 +  [path to file]/TEST Handle Script Error in KM.scpt: ​
 +  execution error: [ERROR]: ​ Can’t divide 5.0 by zero.
 +  ​
 +Unfortunately the Keyboard Maestro Engine log file is very verbose, and it can be very hard to find the actual error. ​ So, you may find this custom macro useful:\\
 +[MACRO: ​  ​Display Last KM Macro Error Ver 4 [Pub]](https://​forum.keyboardmaestro.com/​t/​display-last-km-macro-error/​5340).
 +
 +Also, if you are writing a lot of AppleScripts,​ then you will find it very beneficial to always include a custom error handler in your script, and then use a custom Action after the _Execute AppleScript_ Action to check for an error and provide much better reporting.\\
 +Here is an example of such an Action/​Macro to handle errors: ​ [[KM] Script Error Handler [Sub-Macro] ](https://​forum.keyboardmaestro.com/​t/​km-script-error-handler-sub-macro/​4641).
 +
 +  ​
 +  ​
  
action/Execute_an_AppleScript.txt · Last modified: 2021/07/21 17:58 by JMichaelTX