Forum OpenACS Q&A: Recommended way to throw errors from functions

Hi all,

What's the recommended way to throw errors from functions? It would probably be better if the error can be caught and dealt with.

I've seen code that calls the Tcl "error" command. I don't know if that allows catching.

I looked in the api-doc, but only found ad_ functions that return exception pages, which is not what I'm looking for.

-Roberto

Collapse
Posted by Tom Jackson on

I think Jeff Davis recommended to me that I use ad_script_abort, which calls ad_raise, which formats a nice return -code error.

As far as catching errors, I would only do it where it is used as a control structure, not as a nice way to pretty up the error. Catch hides the source of the error, so it should only be used on the smallest possible piece of code. Otherwise debugging an application requires you to either add a bunch of ns_log statements, or remove the catch.

Collapse
3: Catching errors (response to 1)
Posted by David Walker on
This one gives you a nice error with all the information about what file/function the error is in.

if {[catch { error "some error" } ] } {
    variable errorInfo
    ns_log error $errorInfo
}

Collapse
Posted by Andrew Piskorski on
Yes, of course you can catch the Tcl error command.

David, "variable errorInfo"? Don't you mean global? I use this:

if { [catch { error "It breaks!" } errmsg] } {
   global errorInfo
   set my_error $errorInfo
   ns_log Error $my_error
}
In reality AOLserver Tcl globals are per-thread, so there's really no need to do the extra "set my_error" step, but the example in the Tcl docs does it like the above, so what the heck. Maybe you really need to do it that way in other Tcl environments. (E.g., maybe with multiple interpretors in the same single-threaded process, or with multiple threads in tclsh.)