如何抛出Lua错误?

17

从一个函数中抛出Lua错误并由调用该函数的脚本处理,这是否可能?

例如,以下代码将在注释处引发错误:

local function aSimpleFunction(...)
    string.format(...) -- Error is indicated to be here
end

aSimpleFunction("An example function: %i",nil)

但是我更愿意捕获错误并通过函数调用者抛出自定义错误

local function aSimpleFunction(...)
    if pcall(function(...)
        string.format(...)
    end) == false then
       -- I want to throw a custom error to whatever is making the call to this function
    end

end

aSimpleFunction("An example function: %i",nil) -- Want the error to start unwinding here 

我的意图是在实际使用中,我的函数会更加复杂,我希望能够提供更有意义的错误信息。


2
Lua代码可以通过调用error函数显式地生成错误。 - Tom Blodget
@TomBlodget,把它变成答案? ;) - Paul Kulchenko
@PaulKulchenko - 看来写注释而不是答案的想法相当具有感染性;-) - Egor Skriptunoff
@EgorSkriptunoff,我注意到了 ;) - Paul Kulchenko
@PaulKulchenko,我宁愿看到这个问题被删除,也不想写答案。但是,我确实想帮助提问者学习可理解的文档(如Lua参考手册)是主要参考资料的重要性。我认为这个问题和任何直接回答它的答案对其他人没有帮助。如果问题更广泛一些,那么它们可能会有所帮助。 - Tom Blodget
@TomBlodget:但错误仍然从aSimpleFunction()内部抛出,我已经知道错误会抛出一个错误,但堆栈跟踪不是来自调用者。 - Puddler
3个回答

19
抛出新错误时可以指定错误的堆栈级别。
error("Error Message") -- Throws at the current stack
error("Error Message",2) -- Throws to the caller
error("Error Message",3) -- Throws to the caller after that

通常,错误消息的开头会添加一些关于错误位置的信息。level参数指定如何获取错误位置。使用level 1(默认值),错误位置是调用error函数的位置。level 2将错误指向调用error的函数所在的位置;依此类推。传递level 0可以避免将错误位置信息添加到消息中。

使用问题中给出的示例

local function aSimpleFunction(...)
    if pcall(function(...)
        string.format(...)
    end) == false then
       error("Function cannot format text",2)
    end

end

aSimpleFunction("An example function: %i",nil) --Error appears here 

9

2
捕获错误就像使用pcall一样简单。
My_Error()
    --Error Somehow
end

local success,err = pcall(My_Error)

if not success then
    error(err)
end

毫无疑问,您想知道这是如何工作的。好吧,pcall 在一个 受保护的线程(protected-call)中运行一个函数,并返回一个布尔值,如果运行成功,以及一个值(它返回的内容/错误)。
另外,不要认为这意味着给函数传递参数是不可能的,只需将它们一起传递给 pcall 即可:
My_Error(x)
    print(x)
    --Error Somehow
end

local success,err = pcall(My_Error, "hi")

if not success then
    error(err)
end

如需更多错误处理控制,请参见http://www.lua.org/manual/5.3/manual.html#2.3http://wiki.roblox.com/index.php?title=Function_dump/Basic_functions#xpcall


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接