Reputation: 22515
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
}
}
Upvotes: 5
Views: 3228
Reputation: 23626
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;
}
}
Upvotes: 16
Reputation: 881
This is Joel Etherton's comment paraphrased as an answer. Note that this isn't the best solution (see Ilya Ivanov's answer for better a solution).
But it's simple and if I read your question correctly it's exactly what you asked for:
void errorHandling(Exception e)
{
// Your BUNCH of logic
}
public void Function1(){
try {
do something
}catch(Exception e) {
errorHandling(e);
}
}
public void Function2() {
try {
do something different
}catch(Exception e) {
errorHandling(e);
}
}
Upvotes: 2