Introduction
What I try to achieve is avoiding the need of capturing library exceptions, specially those generated by users, in the presentation layer. Why?
Based on my experience, I have found out that developers, despite the evolution from return codes to exceptions, still forget to do error safe code, and that includes catching exceptions.
So with that in mind, what I tried to do was minimize the code that needs to be written to take care of errors, especially those occurring on code done by some other developer.
Instead of throwing an exception, I could catch it, eventually write it to some log or trace, and then transform that exception into an event.
Any client that uses this code can subscribe to my event and be notified of errors and do whatever it's suitable with them, better he can do this only once, and as such minimizes the chances of blowing up the client application with an uncaught exception.
This is more interesting when we deal with exceptions generated by user interaction. In this case, it's usual to just notify the user to change the way he/she is using the application. I don't think that exceptions should not be thrown from libraries, I just think that some exceptions could be transformed into an event.
With that in mind, here is the delegate that starts this all:
ErrorEventHandler(object sender, ErrorEventArgs e);
And the class that is used to map the exception to an event:
public class Exception2Event
{
public static event ErrorEventHandler Error;
public static void PublishError(int errorCode, string message, Exception e)
{
ErrorEventArgs errArgs = new ErrorEventArgs(errorCode, message, e);
if ( Error != null )
Error(null, errArgs);
}
}
Note that it uses another class ErrorEventArgs as an argument, basically to pass state to the client. You can see the code on the attached file.
So the client can use this in something like:
public class TestThis
{
public TestThis()
{
Exception2Event.Error += new ErrorEventHandler(LogEvent);
}
public void LogEvent(object sender, ErrorEventArgs e)
{
Console.WriteLine(e.ErrorMessage + " " + e.Message);~
}
public static void Main()
{
try
{
TestThis tt;
tt = new TestThis();
int zero = 0;
int i = 10 / zero;
}
catch(Exception e)
{
Exception2Event.PublishError(1, "Divide by 0 is not good :) ", e);
}
}
}
This is growing long, so time for you to think about this. If any of the readers wishes to discuss this further, don't hesitate to email me (psantos at bizarrologia dot com). Even to say, this is totally nonsense :).