Error Handling
Lua Error Messages
When using Lua Functions and methods, incorrect usage will result in an error message being returned. The format of the error message as follows:
@:<line>:<actual_error_message>
Where <line> is the line in the script that produced the error.
Examples of Lua error messages
- Example 1
-
To test this out, open a Console tab and enter the following Lua code, then click on the "Execute" button in the toolbar:
local obj = syslib.getobject("/home")
if obj ~= nil then
return obj:parent()
-- end missing
This will generate a syntax error in the output window of the console because the "if" statement has not been closed properly.
- Example 2
-
Open a new Console tab in the System Config App and enter the following Lua code, then then click on the "Execute" button in the toolbar:
syslib.setvalue("/home/missing object", 34)
This will generate a runtime error in the output window of the console because the defined objspec does not point to a resolvable object:
Catching errors with pcall
In order to catch errors in Lua, pcall can be used to a call a function in protected mode. As stated in the Lua documentation, "this means that any error inside the function is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message". Pcall takes as parameters the function to call and its arguments, if any. Please check the example below:
local create_folder = function(parent, name)
local obj = syslib.createobject(parent, "MODEL_CLASS_GENFOLDER")
obj.ObjectName = name
obj:commit()
end
return function()
-- wrap the function in a pcall and retrieve possible error messages
local success, error = pcall(create_folder, "/home", "new_folder")
if success then
return 'Success'
end
return error
end
This is an example of calling, in protected mode, a function which creates a new folder. The script will return the result of this call: "Success", if no error occurs, or the error message otherwise (for example, in the case when the folder already exists).
Below, there is another example of a function which returns two values - the sum and product of two numbers. If the execution succeeds, pcall will return three values: a boolean (which is "true") and the two values given by the function. Otherwise, there will be only two values returned: the boolean stating that the execution failed ("false") and the error message. We can trigger an error by calling the function with one of the parameters as a non-number.
function sum_and_product(a, b)
return a+b, a*b
end
return function()
local success, v1, v2 = pcall(sum_and_product, 1, 'n')
if success then
return {v1, v2}
end
return v1 -- v1 will contain the error message
end