API xpcall

From Warcraft Wiki
Jump to navigation Jump to search

Executes a function in protected mode with a custom error handler.

status, ... = xpcall(f, err [, ...])
false, errormsg  = xpcall(f, err, arg1, arg2)
true, ret1, ret2 = xpcall(f, err, arg1, arg2)

Arguments

f
function - The function that will be called.
err
function - Error handler function to be used should f cause an error.
...
any - Optional arguments to be passed to the function.

Returns

status
boolean - True if the function succeeded without errors.
...
If status is false, the return from the error function (any). This should generally be a string because the global handler for uncaught errors won't accept non-string errors, it would be replaced by "UNKNOWN ERROR".
if status is true, the return values from the function (list).

Details

Reference: Lua Manual

xpcall calls function f in protected mode, using err as the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall also returns all results from the call, after this first result. In case of any error, xpcall returns false plus the result from err.

Example

This is useful to call a function and continue regardless of any error, which would be caught and handled by showing it in the default error handler.

local function failableFunc(...)
	local t = {}
	t[nil] = 2
end

xpcall(failableFunc, geterrorhandler())
print("hello") -- continues and prints this line

Another example to illustrate the return values and optional arguments.

local function fails(...)
	return 3 + true
end

local function succeeds(...)
	if select("#", ...) > 0 then
		print("optional args", ...)
	end
	return "hello", "world"
end

local function err(s)
	print("error message", s)
	return "oh no!"
end

print(xpcall(fails, err))
> "error message", "Interface\AddOns\Test\Test.lua:3: attempt to perform arithmetic on a boolean value"
> false, "oh no!"

print(xpcall(succeeds, err))
> true, "hello", "world"

print(xpcall(succeeds, err, "banana", 123))
> "optional args", "banana", 123
> true, "hello", "world"

References