Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a 'clear' error message in Lua

I am using the error function in quite a few of my functions and would like to propagate the error messages to the user. However, I obviously don't want to include information about where the error occured exactly; this information should only go to the log files.

For example, I have a class that manages the connection to a server. If the connection times out, it calls

error("Connection timed out!")

The error message is then caught by the calling code via pcall. However, the message contains not only the message I passed, but also the name of the file that caused the error and the line number:

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

The question is: Is there any way to only retrieve the error message itself, or do I have to do this manually like following:

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

Cheers,

like image 423
Henrik Ilgen Avatar asked Oct 01 '22 17:10

Henrik Ilgen


1 Answers

From the documentation of the 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.

From what is stated in the second paragraph, adding a level of 0 to the error call will result in the desired output:

error("Connection timed out!", 0)
like image 148
Tim Cooper Avatar answered Oct 05 '22 11:10

Tim Cooper