开发者

Good practices for leveled debugging and error handling

For debugging开发者_Python百科 my code (low-level problem) I would like to use different levels of debugging, in order to vary how hard my code might reject certain things. So far I have always been using something like this:

enum error_level
{
    el_neglegable = 0,
    el_notable_to_log = 10,
    el_notable_to_print = 100,
    el_terminate_program = 1000,
    /* you can fragment the levels even more, of course */
};

void inline process_error( error_level error )
{
    if( error >= el_notable_to_print ) printf("A notable error has occured!\n");
    if( error >= el_terminate_program ) exit();
    /* you can build in more queries like this, of course */
}

This is only a variation of the theme, but now you have a picture of what I mean. I would like to learn about better practices to employ different levels of debugging, depending on how much I want to remove errors from my program.

Question: Do know you good guidelines, practices and the like, in order to achieve a code that is more maintainable and allows for such a debugging model?


There's absolutely value in being able to characterize error conditions, but characterizing them by severity or action to take means that the decision is made by the wrong piece of code.

My reason for saying that is that the method which encounters the error lacks context.

Consider the situation where a socket connection open fails. What error severity would you want socket.open(host,port) to return? Depending on context, you might:

  • Silently retry
  • Log and retry
  • Throw a dialog up to the user
  • Try another connection in a list
  • Terminate the program
  • etc

The decision of what action to take on an error is totally dependent on context - what it means when a particular error occurs.

For this reason, most people are now following a model in which the method which encounters an error reports that error, and allows the caller to determine what action to take.

So instead of thinking about severity levels, instead you'd have a set of error conditions, and caller would either take an action, or return an error itself (not necessarily the same error).

In this case, socket.open(host,port) would yield an error like socket_open_fails, and caller would have context to know what to do when that socket open fails. It would know whether the socket is used to get vital data without which the program cannot continue, or is more optional (perhaps to get program updates).

So: don't define your error conditions by the action to be taken: define them by what's failed.


As a side note, a good deal of the time it took me to write this was taken in describing this all without referring to exceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜