shanmugharaj
shanmugharaj

Reputation: 3924

How to create a method than can be executed on any exception in C#?

try
{
}
catch (Exception objEx)
{
    clsLog.blnLogError(this.GetType().Name, MethodBase.GetCurrentMethod().Name, String.Format("Error In {0}...", MethodBase.GetCurrentMethod().Name), objEx.Message);
}

This is my Code and I need something like.

catch (MyException objEx)
{
}

class MyException
{
    method()
    {
        //method overload with necessary parameters.
        clsLog.blnLogError(this.GetType().Name, MethodBase.GetCurrentMethod().Name, String.Format("Error In {0}...", MethodBase.GetCurrentMethod().Name), objEx.Message);
    }
}

In that exception class I need to get the curent class name and method name instead of writing every time.

How to achieve this?

UPDATE

[Serializable]
public class MyException : Exception
{
    public MyException(string message, Exception innerException, object obj)
        : base(message, innerException)
    {
    }
}
try
{
    int f = int.Parse("d");
}
catch (MyException objEx)
{
}

It is not catching the exception and I need the method name, class name of the one where it throws error.

Upvotes: 2

Views: 169

Answers (1)

Spontifixus
Spontifixus

Reputation: 6660

This cannot be done by inheriting, you will need to write an extension method so that you can call your logging method on all exception types, no matter whether they were declared by yourself or not.

To create an extension method create a static class containing a static method doing your work. Prepend the first argument of the method with the keyword this, indicating to the compiler that this method can be invoked like a member method on objects of the type of the first parameter (in your case Exception):

public static class ExceptionExtensions
{
    public static void Log(this Exception ex)
    {
        var stackTrace = new StackTrace();
        var callingMethod = stackTrace.GetFrame(1).GetMethod();
        var methodName = callingMethod.Name;
        var className = callingMethod.DeclaringType.Name;
        clsLog.blnLogError(className, methodName, string.Format("Error In {0}...", methodName), ex.Message);
    }
}

then you can call that method on every exception:

try
{
    int f = int.Parse("d");
}
catch(Exception ex)
{
    ex.Log();
}

For more information on extension methods see the C# Programming Guide.

Upvotes: 7

Related Questions