8

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.

Haidar
  • 178
  • 3
  • 12
  • 2
    Only [aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) tools/weavers [like PostSharp](http://www.postsharp.net/) could help you. By the way, more than hundred methods in one class? That's just... *Bad*. At least f rom my perspective. And definitely scary. – Patryk Ćwiek Mar 13 '14 at 11:21
  • That is true, but my business and repository classes have many methods which is making these classes too heavy. Actually the number of methods in a class depends on the complexity of the business rules or the number of operations you want to perform. – Haidar Mar 13 '14 at 11:30
  • 3
    Don't use "throw ex;" because that will destroy your precious call stack. Just write "throw;" and the information in the exception will be preserved. With that said I want to point out that you shouldn't catch exceptions unless you know how to handle them. Reference: http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex – Patrik B Mar 13 '14 at 11:38
  • @Patrik- I understand that I should just write "throw". Your suggestion is to enforce the best practice of error handling. But my situation is different and I want to handle all the class method exceptions at single class level. For all methods in class A must have only one place to handle and log the errors occurred in any method of class A. – Haidar Mar 13 '14 at 12:07

4 Answers4

7

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.

Sourav 'Abhi' Mitra
  • 2,390
  • 16
  • 15
1

You're being too defensive. Don't overuse try..catch only catch it where you need it.

In this case consider catching exceptions thrown by interacting with your class outside of your class. Remember exceptions will be propogated.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
1

Use libraries such as Policy Injection Application Block, Castle, Spring.NET etc. These libraries allow you to inject behaviour as Exception Catching.

Jonathas Costa
  • 1,006
  • 9
  • 27
  • Could you please share some sample code without using any other Library (Policy Injection Application Block, Castle or Spring.NET)? – Haidar Mar 13 '14 at 12:13
  • Unfortunaly these libraries implement Proxy Design Pattern and deal with a lot of Reflection etc. If I skip this plumbing, I will have to code a lot... – Jonathas Costa Mar 13 '14 at 12:29
1

Just implement DispatcherUnhandledException in you App.xaml.cs; it will handle all your exceptions;

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogError(e);
// MessageBox.Show(e.Exception.Message);
            e.Handled = true;
        }
mohammad jannesary
  • 1,811
  • 1
  • 26
  • 27