Richard Collette
Richard Collette

Reputation: 5703

Asp.Net OData V4: How can I get exceptions to bubble up to a global handler?

I am relatively new to Asp.Net OData. What I have realized is that the ODataMediaTypeFormatter logs exceptions like JSON deserialization issues and does not throw an exception. So I created a ModelValidationFilterAttribute and enabled it globally through HttpConfiguration.

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response =
                actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    actionContext.ModelState);
        }
    }
}

The problem with this is that things like System.InsufficientExecutionStackException also get sent down to the client using this validation filter.

I want model validation state to be sent to the client when there is an error in the model format/data. For code exceptions, I would prefer that the exception just bubble up to a global handler where I can log, check the exception type, and respond to the client accordingly.

Upvotes: 0

Views: 1925

Answers (1)

Tan Jinfu
Tan Jinfu

Reputation: 3347

You may want to create an exception filter like this:

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

then you can control how to respond to the client. In the above example, it send 501 to the client.

References:

  1. http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

  2. http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling

Upvotes: 2

Related Questions