tags:

views:

29

answers:

2

Hello friends,

Ineed to write the Error Handler Helper classes for my asp.net mvc project..

can anybody give me the code how to write and where to write this Helper classes in my appliction?

and I need to use this Error to log in controller level.. I dont want to use try and catch block for each and every Actionresult in my control.. I need to use controller level?

cananybody help me out?

thanks

+1  A: 

write error logging for you? hmmmm. Fortunately someone already has: You need log4net

BritishDeveloper
+2  A: 

I can suggest you to use elmah. It is great for error logging, you can read about it from here: http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

What I have done, and I am happy with it is the following. I have done a custom handle error attribute, which has the following code:

public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{

    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);

        var e = context.Exception;
        if (!context.ExceptionHandled   // if unhandled, will be logged anyhow
            || ExceptionHelper.RaiseErrorSignal(e)      // prefer signaling, if possible
            || IsFiltered(context))     // filtered?
            return;

        ExceptionHelper.LogException(e);
    }


    private static bool IsFiltered(ExceptionContext context) 
    {
        var config = context.HttpContext.GetSection("elmah/errorFilter") 
                     as ErrorFilterConfiguration;

        if (config == null) 
            return false;

        var testContext = new ErrorFilterModule.AssertionHelperContext(
                                  context.Exception, HttpContext.Current);

        return config.Assertion.Test(testContext);
    }
}

And I have an ExceptionHelper class with this code:

public static class ExceptionHelper
{
    public static bool RaiseErrorSignal(Exception e)
    {
        var context = HttpContext.Current;
        if (context == null)
            return false;
        var signal = ErrorSignal.FromContext(context);
        if (signal == null)
            return false;
        signal.Raise(e, context);
        return true;
    }

    public static void LogException(Exception e)
    {
        var context = HttpContext.Current;
        ErrorLog.GetDefault(context).Log(new Error(e, context));
    }

Then I have annotated my base controller class with MyNamspace.HandleError and now all exceptions are handled and logged, I even get a mail when something goes wrong....

apolka
mate, +1 for patience with a 'write code for me' person
BritishDeveloper