Globally catching errors?

Posted by j0nas on Mon 06 Oct 2008 08:02 AM — 2 posts, 11,495 views.

#0
I'd like to catch any errors that occur in my main script, no matter where they happen. As I have a lot of code throwing a try-catch wrapper into every function would be bothersome, is there a better way to go about this?

Can I replace some sort of global error-function, or register some callback?
Australia Forum Administrator #1
Well you could do it like this:


mystuff = {}

function mystuff.a (name, line, wildcards)

  print "in mystuff.a"
  
  b = 2 + "foo"   -- should raise error
  
end -- function

function mystuff.b (name, line, wildcards)

  print "in mystuff.b"
  
end -- function

function my_handler (name, error)
  print ("got error", error, "in", name)
end -- my_handler

function make_stub (name, func)

  return function (...)
     local ok, result = pcall (func, ...)  -- call original function

     if not ok then  -- failure?
       my_handler (name, result)
       return
     end -- if not ok

     return result  -- ok return
     end -- function

end -- make_stub

for k, v in pairs (mystuff) do
  mystuff [k] = make_stub (k, v)
end -- for



What I have done here is simplify things by putting all my functions into a table "mystuff" - just so I know which functions need to be put into try-catch. (You can put mystuff.a as the function name in a trigger).

Then as part of loading the script file I go through the mystuff table, making a stub routine for each function, which replaces the original function. The stub function does a protected call (pcall) and tests the result. On failure, it calls my handler script (my_handler) passing the name of the function and the error message. You could then handle errors in your own way.

For example, if I type into the command line: /mystuff.a ()

Then I see this in the output window:


in mystuff.a
got error [string "Script file"]:7: attempt to perform arithmetic on a string value in a