How to get the errormessage in the error handler for an xpcall()

I am trying to make a nice error handling system and decided to try to use xpcall() for it, but I have run into an issue. I need to have access to the errorMessage in order to have the error handler work right (it uses string.find()), but I can’t figure out how to.

Pretty simple question, how would I use the error message from the regular function of an xpcall() in the error handling function if it fails.

For instance:

local success, returnMessage = xpcall(function()
      error("this is an error")
end, function()
      print(returnMessage)
end)

basically, how would I get the print statement in the error handler to print the returnMessage, or error that was thrown in the main function.

For your needs you would be better using a pcall because xpcall’s “error message” is the return value of the error handler function.

Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall() also returns all results from the call, after this first result. In case of any error, xpcall() returns false plus the result from err.
Lua Globals | Documentation - Roblox Creator Hub

local function errorHandle(errorMsg)
    if string.find(errorMsg,"404") then
      --Do stuff
   end
end

local success, err = pcall(function()
   --Do Stuff
end)

if not success then errorHandle(err) end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.