I have several C# methods that I want to wrap in a try-catch block. Each function will have the same logic for the catch. Is there an elegant way to add a decorator to each of these functions so they are all wrapped with the same try/catch block? I don't want to add the try/catch block to all of these functions.
Example:
public void Function1(){
try {
do something
}catch(Exception e) {
//a BUNCH of logic that is the same for all functions
}
}
public void Function2() {
try {
do something different
}catch(Exception e) {
//a BUNCH of logic that is the same for all functions
}
}
What about some functional solution to this? Notice I don't swallow exceptions and use throw;
statement, that will re-throw exception keeping its original stack trace. Don't silently swallow exceptions - it's considered to be a very bad practice and the debugging code gets horrible.
void Main()
{
WrapFunctionCall( () => DoSomething(5));
WrapFunctionCall( () => DoSomethingDifferent("tyto", 4));
}
public void DoSomething(int v){ /* logic */}
public void DoSomethingDifferent(string v, int val){ /* another logic */}
public void WrapFunctionCall(Action function)
{
try
{
function();
}
catch(Exception e)
{
//a BUNCH of logic that is the same for all functions
throw;
}
}
If you need to return some value, the signature for WrapFunctionCall
method will change
void Main()
{
var result = WrapFunctionCallWithReturn( () => DoSomething(5));
var differentResult = WrapFunctionCallWithReturn( () => DoSomethingDifferent("tyto", 4));
}
public int DoSomething(int v){ return 0; }
public string DoSomethingDifferent(string v, int val){ return "tyto"; }
public T WrapFunctionCallWithReturn<T>(Func<T> function)
{
try
{
return function();
}
catch(Exception e)
{
//a BUNCH of logic that is the same for all functions
throw;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With