CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Grant Killian's Blog

No, this has nothing to do with beer -- but maybe it should?

Async Exception Handling

Before I went away on holiday, a few people asked me about exception handing for asynchronous methods -- possibly because they were experimenting with the various async examples I had blogged about.  While I don't have a lot of time (I'm supposed to be writing a lot of code documentation for a project I'm on --yuck), I need a break so let me share the error handling mechanism I usually employ for asynchrounous methods.  It's nothing more sophisticated than adding an "ErrorText" member variable to the custom eventargs class; I pass types of this eventargs class to my callback function and, therefore, the callback function can examine the value of the property to see if there is any error text to deal with.  This class serves as the messenger between the threads of execution.

My custom eventargs class looks something like this (I've omitted the propery sets and gets and some other code for brevity):
 public class StatusEventArgs : EventArgs
 {
  public string ErrorText;
  public StatusEventArgs()
  {
   this.ErrorText = "";
  }
 }

When an exception is raised, I simply assign a value to the ErrorText property in the catch portion of my try-catch block (e.ErrorText = ex.ToString() ) and then I use the callback method I discussed earlier to communicate the condition back to the client.

Nothing too fancy, I treat Exceptions in the async component like state in any other business object.  There's many angles you could take with this.  You could expose a generic Exception object from the StatusEventArgs class instead of the string variable and use e.TheExceptionObject = ex; you'd have access to the full exception type generated by the asynchronous method this way.  I know some people who prefer using integer values to communicate Exception severity to the client, and this model would certainly accomodate that.  Others may want to use a simple boolean for success or failure, and again the approach I present will suffice.  The point is, extend the object you pass back and forth for asynchronous communications to include any error information you may be interested in.

Happy .Netting!



Comments

Grant said:

Sometimes I choose the string instead of the full Exception object when I don't want my client application to have to wrestle with particularities of the error message; for example, if I'm just bubbling up the error message, I'll "pretty format" the string variable in my EventArgs class instead of passing the full blown object.

It boils down to what your exception handling logic is doing.
# September 25, 2003 4:55 AM

Paul Laudeman's Blog said:

Windows Forms Common Tasks
# April 10, 2004 1:11 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!