Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch all exceptions at class level in CSharp?

I have a class like:

class SampleRepositoryClass
{
    void MethodA()
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }        
    }

    void MethodB(int a, int b)
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }
    }

    List<int> MethodC(int userId)
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }
    }
}

In above example, you can see that in each methods (MethodA, MethodB, MethodC) have try...catch blocks to log the errors and then throw to higher level.

Imagine that when my Repository class might have more than hundred methods and in each method I have try...catch block even if there is only single line of code.

Now, my intention is to reduce these repetitive exception logging code and log all the exceptions at class level instead of method level.

like image 368
Haidar Avatar asked Mar 13 '14 11:03

Haidar


1 Answers

Why re-invent the wheel, when there is such a thing as FREE Post Sharp Express. It's as easy as adding the PostSharp.dll as a reference to your project. After doing that, your repository would look like the following:

[Serializable]
class ExceptionWrapper : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        LogError(args.Exception);
        //throw args.Exception;
    }
}

[ExceptionWrapper]
class SampleRepositoryClass
{
    public void MethodA()
    {
        //Do Something
    }

    void MethodB(int a, int b)
    {
        //Do Something
    }

    List<int> MethodC(int userId)
    {
        //Do Something
    }
}

Adding the ExceptionWrapper attribute on the class, ensures all properties and methods are encapsulated within a try/catch block. The code in catch will be the code you put in the overriden function OnException() in ExceptionWrapper.

You dont need to write code to rethrow as well. The exception can also be automatically re-thrown if correct flow-behaviors are provided. Please check the documentation for that.

like image 54
Sourav 'Abhi' Mitra Avatar answered Oct 09 '22 14:10

Sourav 'Abhi' Mitra