错误处理 – 在Lua中获取“清除”错误消息

我在我的很多函数中使用了错误函数,并希望将错误消息传播给用户.但是,我显然不希望包含有关错误发生位置的信息;此信息应仅转到日志文件.

例如,我有一个管理服务器连接的类.如果连接超时,则调用

error("Connection timed out!")

然后,调用代码通过pcall捕获错误消息.但是,该消息不仅包含我传递的消息,还包含导致错误的文件名和行号:

common/net/enetclient.lua:21: Connection timed out!

问题是:有没有办法只检索错误消息本身,或者我必须手动执行此操作,如下所示:

local status, msg = pcall(someFunctionThatThrowsErrors)
if not status then
    local file, msg = msg:match("(.-:%d+): (.+)")
    print("Error: " .. msg)
end

干杯,

最佳答案
error function的文档:

error (message [, level])

Terminates the last protected function called and returns message as the error message. Function error never returns.

Usually, error adds some information about the error position at the beginning of the message, if the message is a string. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

根据第二段中的说明,在错误调用中添加0级将产生所需的输出:

error("Connection timed out!", 0)

转载注明原文:错误处理 – 在Lua中获取“清除”错误消息 - 代码日志