加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 00:16:06 所属栏目:大数据 来源:网络整理
导读:我在我的很多函数中使用了错误函数,并希望将错误消息传播给用户.但是,我显然不希望包含有关错误发生位置的信息;此信息应仅转到日志文件. 例如,我有一个管理服务器连接的类.如果连接超时,则调用 error("Connection timed out!") 然后,调用代码通过pcall捕获错
我在我的很多函数中使用了错误函数,并希望将错误消息传播给用户.但是,我显然不希望包含有关错误发生位置的信息;此信息应仅转到日志文件.

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

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读