このモジュールは他のモジュールでエラー処理を簡略化するために使用されます。エラーを投げる可能性のある関数を変換して、エラーを投げる代わりにエラーメッセージを返すようにします。
使い方
[ソースを編集]local protect = require('モジュール:Protect')
local protectedFunc = protect(func, errFormat, options)
引数
[ソースを編集]- テンプレート:Code
- 変換される関数。
- テンプレート:Code (default: テンプレート:Code)
- 返されるエラーメッセージの書式。
- テンプレート:Codeが返すエラーメッセージはテンプレート:Codeとして指定します。
- テンプレート:Code – 引数のテーブル。下記のキーが指定できます。
- テンプレート:Code(既定値:false)
- trueの場合、テンプレート:Codeの書式でエラーメッセージを返します。falseの場合、
<strong class="error">で囲んで返します。
- trueの場合、テンプレート:Codeの書式でエラーメッセージを返します。falseの場合、
- テンプレート:Code(既定値:true)
- trueの場合、エラーメッセージから位置情報(エラーが起こったモジュールと行番号)を除去します。
- テンプレート:Code(既定値:false)
戻り値
[ソースを編集]戻り値のテンプレート:Codeは関数であり、渡された引数をそのままテンプレート:Codeに渡し、その戻り値はそのままテンプレート:Codeの戻り値になります。テンプレート:Codeがエラーを投げた場合、テンプレート:Codeエラーを投げず、代わりにエラーメッセージを返します。
使用例
[ソースを編集]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関数を引数なしで呼び出すと、エラー: 引数未入力と返されます。 テンプレート:Sandbox other
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