Frage

I'm trying to get up and running with Elmah for an MVC 5 WebAPI app. All the docs I'm finding seem to start and end with "install it via nuget" and just assume that'll cover it, but I'm clearly missing something. I've installed Elmah.MVC 2.1.1 via nuget, and I am able to view the error log at /elmah. I'm able to request an invalid route and see that the resulting 404 error is getting logged by Elmah, even with customErrors turned on. However, if I generate an unhandled error within a controller, or during controller instantiation, nothing is getting logged to Elmah. For instance:

[HttpGet, Route("api/health")]
[ApiExplorerSettings(IgnoreApi = true)]
public HttpResponseMessage GetHealth()
{
    throw new Exception("Whoops.");
}

I can call this all day long and nothing shows up in the Elmah log. Adding the standard HandleError attribute doesn't change anything, and the little bit of docs here seems pretty explicit that I shouldn't have to create a custom HandleError attribute.

I use Ninject for DI, and similarly if I break a dependency binding I'll get a nice error like this:

{
    Message: "An error has occurred."
    ExceptionMessage: "An error occurred when trying to create a controller of type 'HealthController'. Make sure that the controller has a parameterless public constructor."
    ...
}

But nothing makes it to the Elmah log in that case either.

I assume in both cases this is because MVC is handling those errors for me (formatting the exceptions as JSON, etc) and not passing them on to Elmah. How do I configure things so that any exception not handled within a controller is logged by Elmah?

War es hilfreich?

Lösung

Figured it out. This is similar to the older ExceptionFilter mechanism, but more global as ExceptionFilters only work with unhandled exceptions from a specific controller and not errors that may crop up higher in the stack. First, I needed a simple ExceptionLogger to pass exceptions to Elmah:

public class ElmahExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(context.Exception));
    }
}

Then added that in WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
}

This does require the latest and greatest MVC/WebAPI (5.1.1 currently).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top