Gammon Forum
Entire forum
MUSHclient
Lua
Globally catching errors?
Globally catching errors?
|
It is now over 60 days since the last post. This thread is closed.
  Refresh page
Posted by
| j0nas
(56 posts) bio
|
Date
| Mon 06 Oct 2008 08:02 AM (UTC) |
Message
| 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? | top |
|
Posted by
| Nick Gammon
Australia (22,973 posts) bio
Forum Administrator |
Date
| Reply #1 on Tue 07 Oct 2008 05:07 AM (UTC) |
Message
| 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
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|
The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).
To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.
8,015 views.
It is now over 60 days since the last post. This thread is closed.
  Refresh page
top
Quick links:
MUSHclient.
MUSHclient help.
Forum shortcuts.
Posting templates.
Lua modules.
Lua documentation.
Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.