in reply to The art of error handling

The short fall of mirod's scheme is that is usually only one right answer, but there infinite wrong answers. For example, if I write some code that opens a file for reading, many things can go wrong. The file might not exist, the file might not be readable by the current user, the file might be empty, etc. If you are trying to give meaningful errors to the calling routines, you have exhausted the 0 or undef on failure option. All the calling code can do is say "Yup, something bad happened".

This gets even more complex when the low level routines are interacting with system(). To continue the example above, lets say the subroutine opens a file, reads a command from it and executes it via system() ( yes, security sucks, but this is an example ). You have not only the problems listed above, but now you need to worry about the error codes generated by the system() call as well.

My general method ( I am contemplating shining this up and attempting to present it at YAPC ) is I have a module that provides a series of simple functions ( Debug, Warn, Error, Usage, Notify ), a series of control variables ( don't print the message, die when Error is called, etc. ) and a whole slew of constants. The constants are defined in a hash, and the import routine makes constant functions of them and shoves them into the caller's space. There is one special value - NO_ERROR which is numerically 0. I use this since system() returns 0 on success ( it has some other interesting side affects ). The defined error codes are negative and any system() call returns the correctly left shifted response on error.

This allows the calling functions to determine if the error was internal ( eg, "Before I can do x, you need to give me y and z" ) or external ( eg, "That command does not exist" ). With a few more functions, you can even turn the numeric code back into something a bit more human readable.

Returning useful error codes is difficult at best. This is a long-winded statement of my current solution to this problem in the hopes it may help you. Sorry for the lack of code. If enough interest is given, I may clean the module up enough for the Catacombs.

Mik
mikfire

Replies are listed 'Best First'.
Re: Re: The art of error handling
by mirod (Canon) on Dec 19, 2000 at 22:14 UTC

    I agree my method is not perfect, I'm just saying that I try to use it as often as possible. It also makes me write simple, atomic functions that do only one thing and that return either a valid result or a single failure. And the calling code most of the time dies in case of failure.

    I find it very rare that a function should fail but the calling code will behave differently depending on the error