Problem
I am working on a fluent interface for exception handling.
Here’s how it looks :
On<NullReferenceException>()
.First.LogTo("errors")
.Then.TranslateTo("null object");
On<FileNotFoundException>()
.First.Translate(excpetion => excpetion.Message)
.Then.LogTo("errors");
On<InvalidOperationException>()
.If(excpetion => excpetion.Message.Contains("This is a test"))
.First.DoSomethingElse(exception => Console.WriteLine(exception.Message));
On<ArgumentException>().Ignore();
Do you think it’s as fluent as it should be ? can I make it better ? any suggestions ?
Solution
I would remove the First and Then methods and just execute actions in the order they are declared.
On<InvalidOperationException>()
.If(excpetion => excpetion.Message.Contains("This is a test"))
.First.DoSomethingElse(exception => Console.WriteLine(exception.Message));
Is a bit confusing to me regarding scoping of the individual branch. If you want to do more than one thing after the if statement, how are you supposed to do it? I assume that your code will call the lambda in DoSomethingElse()
if the condition is true. If that was followed by .Then.LogTo("errors");
, would the execution of the LogTo
also be conditional based on the If
?
Perhaps, if you can make it clearer what is done in each specific case it would be easier to read this scoping. Say for instance,
On<InvalidOperationException>()
.If(excpetion => excpetion.Message.Contains("This is a test"), whentrue => {
whentrue.SomethingElse(exception => Console.WriteLine(exception.Message))
.LogTo("console");
},
otherwise => otherwise.LogTo("eventLog");