示例工程 20-error-handling

20-error-handling/02-structured-error-object/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:error 可携带任意对象;pcall 原样返回。
local M = {}
 
local function validate(value)
	if type(value) ~= "number" then
		error({ code = "E_TYPE", field = "value" }, 0)
	end
	return value
end
 
--- @return table { ok = boolean, code = string }
function M.run(log)
	log = log or print
	local ok, err = pcall(validate, "x")
	log(("ok=%s code=%s"):format(tostring(ok), tostring(ok and "none" or err.code)))
	return { ok = ok, code = ok and "none" or err.code }
end
 
if not ... then
	M.run()
end
return M