モジュール:Protect
このモジュールは他のモジュールでエラー処理を簡略化するために使用されます。エラーを投げる可能性のある関数を変換して、エラーを投げる代わりにエラーメッセージを返すようにします。
使い方
[編集]local protect = require('モジュール:Protect')
local protectedFunc = protect(func, errFormat, options)
引数
[編集]func- 変換される関数。
errFormat(default:'エラー: %s')- 返されるエラーメッセージの書式。
funcが返すエラーメッセージは'%s'として指定します。
options– 引数のテーブル。下記のキーが指定できます。raw(既定値:false)- trueの場合、
errFormatの書式でエラーメッセージを返します。falseの場合、<strong class="error">で囲んで返します。
- trueの場合、
removeLocation(既定値:true)- trueの場合、エラーメッセージから位置情報(エラーが起こったモジュールと行番号)を除去します。
戻り値
[編集]戻り値のprotectedFuncは関数であり、渡された引数をそのままfuncに渡し、その戻り値はそのままprotectedFuncの戻り値になります。funcがエラーを投げた場合、protectedFuncエラーを投げず、代わりにエラーメッセージを返します。
使用例
[編集]local protect = require('Module:Protect')
local p = {}
function p.main(frame)
if not frame.args[1] then
error('引数未入力')
end
return frame.args[1]
end
p.main = protect(p.main)
return p
main関数を引数なしで呼び出すと、エラー: 引数未入力と返されます。
local function processResult(options, success, ...)
if not success then
local message = tostring(... or '(メッセージなし)')
if options.removeLocation then
message = string.gsub(message, '^Module:[^:]+:%d+: ', '', 1)
message = string.gsub(message, '^モジュール:[^:]+:%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 'エラー: %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