Foldr Zen Zone

MaSH

Handling Errors

At some point your script will encounter an error. It could be a failed HTTP request or an attempt to process an invalid file type. MaSH allows you to respond to these errors using the mash.error object and an error block.

The Error Object

When a mashlet encounters an error that error is assigned to the mash.error object. This object has three properties message, line and expression.

Properties

message: String get

A useful message which explains why the error occurred.

line: Number get

The line number of the script where the error occurred.

expression: String get

The line of code within the script which caused the error.

The Error Block

An error block can be placed anywhere in your script and will be called when an error occurs in the previous expression. Error blocks can be extremely helpful, for example we can use them to notify an administrator that a script has failed or call exit which will prevent the script from continuing any further.

Natural

mash
# Make a HTTP request with a deliberately invalid URL

set response to mash.http.get("https://invalid")
error
    printline "Error: {{mash.error.message}}"
    printline "Line: {{mash.error.line}}"
    printline "Expression: {{mash.error.expression}}"
    exit
end

# This will not be called
printline "This will not be printed"

Standard

mash
# Make a HTTP request with a deliberately invalid URL

response = mash.http.get("https://invalid")
error
    printline("Error: {{mash.error.message}}")
    printline("Line: {{mash.error.line}}")
    printline("Expression: {{mash.error.expression}}")
    exit
end

# This will not be called
printline("This will not be printed")

Output

output
Error: cURL error 6: Could not resolve host: invalid; Unknown error (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://invalid
Line: 3
Expression: set response to mash.http.get("https://invalid")

Stopping a script with fail

In our previous script we called exit when an error occurred to halt the script’s execution. By using exit the MaSH runtime assumes that the mashlet executed successfully and your log files will reflect this. Instead we can use a fail statement to halt our script and cause the runtime to log an error instead. Below is the previous script but using fail instead of exit.

Natural

mash
# Make a HTTP request with a deliberately invalid URL

printline "This will be printed"

set response to mash.http.get("https://invalid")
error
    fail mash.error.message
end

# This will not be called
printline "This will not be printed"

Standard

mash
# Make a HTTP request with a deliberately invalid URL

printline("This will be printed")

response = mash.http.get("https://invalid")
error
    fail mash.error.message
end

# This will not be called
printline("This will not be printed")

Output

output
This will be printed
Every journey begins with a single step

Declutter, Focus, Zone In. Repeat.

Begin your File Zen Journey