Module:Protect

From Nordic Larp Wiki
Jump to navigation Jump to search

This metamodule simplifies error handling in other modules. It transforms a function, which may throw an error, into a function, which returns a specified error message in that case.

Usage

local protect = require('Module:Protect')
local protectedFunc = protect(func, errFormat, options)

Arguments

  • func
    Function to be transformed.
  • errFormat (default: 'Error: %s')
    Custom error message.
    Use '%s' to include the message from a caught error.
  • options – optional table with the following fields:
    • raw (default: false)
      If true, then errFormat will be used as is, otherwise it will be wrapped inside a tag <strong class="error">.
    • removeLocation (default: true)
      If true, removes location information from caught error messages.

Return value

The resulting protectedFunc is a function, which calls the original function func, passing all arguments to it, and returns all its return values. If func throws an error, the specified error message is returned instead.

Example

local protect = require('Module:Protect')

local p = {}

function p.main(frame)
    if not frame.args[1] then
        error('missing argument')
    end
    return frame.args[1]
end

p.main = protect(p.main)

return p

Invoking the main function without arguments will output: Error: missing argument


local function processResult(options, success, ...)
	if not success then
		local message = tostring(... or '(no message)')
		if options.removeLocation then
			message = string.gsub(message, '^Module:[^:]+:%d+: ', '', 1)
		end
		return string.format(options.errFormat, message)
	end
	return ...
end

local function protect(func, errFormat, options)
	if type(errFormat) == 'table' then
		options = options or errFormat
		errFormat = nil
	end
	options = mw.clone(options) or {}
	options.errFormat = errFormat or options.errFormat or 'Error: %s'
	if not options.raw then
		options.errFormat = '<strong class="error">' .. options.errFormat .. '</strong>'
	end
	options.removeLocation = options.removeLocation == nil or options.removeLocation
	
	return function (...)
		return processResult(options, pcall(func, ...))
	end
end

return protect