Catching Errors
We’ve mentioned a few times by now that you should always test whether it’s safe to let a script do something. Two of the examples we’ve seen are the following:
if (app.selection[0].constructor.name != "InsertionPoint") if (myString == "nonsense")
These two checks are specific: the first one tests whether a
selection is an insertion point; in the second one we make sure that we do
something only if the variable myString
has a particular value. We use specific tests like these when we are well
aware of what could go wrong.
However, we often don’t know what could go wrong, or we might run into problems because of several reasons. Trying to list the possible error conditions could be tedious, and you never know if you’ve got them all. To deal with these situations, you can use JavaScript’s general error catcher. Let’s force an error. Place the cursor in some text in an InDesign document, then run this script:
try
{
app.selection[0].contents = 3
}
catch (myError)
{
alert (myError);
exit ()
}What we want to do goes in the block under try. Any error that occurs during the execution
of the clause(s) in the try block are
caught by the catch statement and the
script passes control to the script code in the catch block.
Here, we’ve chosen to display the error and to halt the script. You could also decide that at some stage in the script something could go wrong, but you’re not interested to know the problem: all you care about is that the script gets on with it. In that case you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access