kkocabiyik
kkocabiyik

Reputation: 4416

FilterExceptionAttribute not getting exception in Asp.net Web Api

I throw an exception over my controller action and trying to get my exception with ExceptionFilterAttribute like below

using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using Newtonsoft.Json;
using Presentation.Client.Api2.Models;
using ExceptionFilterAttribute = System.Web.Http.Filters.ExceptionFilterAttribute;

public class ExceptionWrapAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext filterContext)
    {
        var exception = filterContext.Exception as Core.Exceptions.MyException;
        var response = ResponseDTO.CreateDynamicResponseFromException(exception);
        var message = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(JsonConvert.SerializeObject(response))
        };
        filterContext.Response = message;
        base.OnException(filterContext);
    }
}

However at line var exception = filterContext.Exception as Core.Exceptions.MyException; exception becomes null even though I throw new MyException() from my controller's action. In addition to this, when I look at the debugger it says that filterContext.Exception is "object reference not set to an instance of an object" . How is that possible? I'm using Asp.Net Web Api.

Upvotes: 1

Views: 1739

Answers (1)

kkocabiyik
kkocabiyik

Reputation: 4416

I've managed to solve the problem. I got another attribute called ResponseWrapAttribute which stands for wrapping normally returned object into generic response. The problem is whenever action throws an exception it enters ResponseWrapAttribute first and ResponseWrap tries to convert object that is already null. What I have done is like below in ResponseWrapAttribute

public class ResponseWrapAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(HttpActionExecutedContext filterContext)
    {

        if (filterContext.Exception == null)
        {

            var content = filterContext.Response.Content as ObjectContent;

            var response = ResponseDTO.CreateDynamicResponse(content.Value);

            ((ObjectContent)filterContext.Response.Content).Value = response;

        }
        base.OnActionExecuted(filterContext);

    }

}

Upvotes: 0

Related Questions