微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误处理 – 在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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐