Search code examples
lualuasql

Catch the LuaSQL error to the xpcall error handler function


How can I get the error output from the LuaSQL driver as an argument to the xpcall error function as assert does?

For example, by running the following code:

local conn =  assert (env:connect("demo_database",config.db.username,config.db.password,config.db.host))

I'm getting the following error:

LuaSQL: error connecting to database. MySQL: Access denied for user 'user_1'@'host1' (using password: YES)

But when I'm running the following code:

local function myerrorhandler( err )
    local file = assert( io.open( "/tmp/testout.txt", "w" ) )
    file:write( err.." - error\n" )
    file:close()
end

local conn = xpcall (env:connect("demo_database",config.db.username,config.db.password,config.db.host), myerrorhandler)

The error I'm getting in the log file is: attempt to call a nil value - error


Solution

  • xpcall expects the first argument to be a function, which it will call and catch errors from. You are basically doing xpcall(func(), handler), i.e. calling func instead of just passing it to xpcall, similar to how pcall expects a function as first argument.

    You basically want to wrap your code in a function:

    local conn = xpcall(function()
        return env:connect("demo_database", config.db.username, config.db.password, config.db.host)
    end, myerrorhandler)