我在我的很多函数中使用了错误函数,并希望将错误消息传播给用户.但是,我显然不希望包含有关错误发生位置的信息;此信息应仅转到日志文件.
例如,我有一个管理服务器连接的类.如果连接超时,则调用
@H_502_4@error("Connection timed out!")然后,调用代码通过pcall捕获错误消息.但是,该消息不仅包含我传递的消息,还包含导致错误的文件名和行号:
@H_502_4@common/net/enetclient.lua:21: Connection timed out!问题是:有没有办法只检索错误消息本身,或者我必须手动执行此操作,如下所示:
@H_502_4@local status,msg = pcall(someFunctionThatThrowsErrors) if not status then local file,msg = msg:match("(.-:%d+): (.+)") print("Error: " .. msg) end干杯,
解决方法
从
error
function的文档:
@H_502_4@error("Connection timed out!",0)
error (message [,level])
Terminates the last protected function called and returns
message
as the error message. Functionerror
never returns.Usually,
error
adds some information about the error position at the beginning of the message,if the message is a string. Thelevel
argument specifies how to get the error position. With level 1 (the default),the error position is where theerror
function was called. Level 2 points the error to where the function that callederror
was called; and so on. Passing a level 0 avoids the addition of error position information to the message.