سؤال

I have an MVC 4 web application. Using ELMAH, and Elmah.Contrib.WebApi, any exceptions that occur within my controllers, or API controllers (or their underlying services) are logged perfectly.

Where I run into trouble is with manually logging of errors. Specifically, inside my Global.asax, I have lots of initialization code (setting up automapper and the like). In order to catch problems which might happen in the initialization code, I have the following:

 protected void Application_Start()
    {
        try
        {
            ControllerBuilder.Current.SetControllerFactory(new ErrorHandlingControllerFactory());
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());

            AutoMapperConfiguration.Configure();
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            DatabaseConfig.Initialize();
            SecurityConfig.Initialize();
        }
        catch (Exception e)
        {
            var context = HttpContext.Current;
            var signal = ErrorSignal.FromContext(context);
            if (signal != null)
            {
                signal.Raise(e, context);
            }
        }
    }

Any exception caught inside the "catch" block will never be logged by ELMAH. Yet, I know that ELMAH is working because any other exceptions that will occur from this point on, inside any controller, will be logged. Therefore I have ruled out problems in the web.config, and the like.

Any suggestions? Thanks.

هل كانت مفيدة؟

المحلول

When the Applicaiton is executing the code in Application_Start it is still being initialized, and it is not handling any HttpRequest.

So the problem with your code is that HttpContext is null. In fact, the line ´ErrorSignal.FromContext(context);´ will throw an ArgumentNullException.

However, you can still use Elmah when there is no HttpContext (and it will basically log the error message and stack trace) as explained in this question.

So your catch would be:

catch (Exception e)
{
    ErrorLog.GetDefault(null).Log(new Error(e));
}

Hope it helps!

نصائح أخرى

I'm a newbie to Elmah but have had luck with something like this:

catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
            return Json(string.Format("Failure: {0}", ex.Message), JsonRequestBehavior.AllowGet);
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top