Question: Getting WebApi Exception Response in an Exception Filter

Question

Getting WebApi Exception Response in an Exception Filter

Answers 2
Added at 2016-12-26 17:12
Tags
Question

We installed an Exception filter

public class APIErrorHandlerAttribute : ExceptionFilterAttribute, IExceptionFilter
{
     // Sets up log4net logger
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger
        (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Exception"
            });

        }

        //Log Critical errors
        log.Info("/****************** API Begin Error ******************/");
        log.Info("Exception:" + context.Exception + "  Case:" + CaseHelper.GetCurrentCaseID() + "  UserID:" + UserHelper.GetCurrentUserID());
        log.Info("/****************** API End Error ******************/");

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(string.Format("Message: {0}\nStack Trace: {1}", context.Exception.Message, context.Exception.StackTrace)),
            ReasonPhrase = "Critical Exception",
        });
    }
}

for all WebApi routes

    //*** Log API Error Globally using Log4net
    public static void RegisterFilters(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute("DefaultApiError", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
        config.Filters.Add(new LRAPIErrorHandlerAttribute());
    }

We also have an authorization attribute that we attach to some controllers. It looks something like this:

public class LegalRadiusAPIAuthorizationAttribute : ActionFilterAttribute, IActionFilter, IFilter
{
    public string Permissions { get; set; }
    public string Roles { get; set; }
    public string Users { get; set; }

    public override void OnActionExecuted(HttpActionExecutedContext filterContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            throw new HttpResponseException(HttpStatusCode.NonAuthoritativeInformation); //203
        }
     }
}

So, if an unauthenticated user hits a route that requires him to be logged in, we throw. If I debug inside this filter and open up the exception dialog I can see the following properties on the exception object:

enter image description here

If I look at the Response prop I see all the pertinent details of the exception thrown.

The problem is when this exception gets handled by APIErrorHandlerAttribute. By the time the exception gets to the handler I can't seem to find the Response property of the exception in context.Exception...

enter image description here

Even though, at the handler I get the following error message from the caught exception:

Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.

implying that the exception in context should have that property.

I feel like I'm having scope issues and that the original exception object that was thrown in the filter isn't in the context parameter of the Exception Handler.

Answers to

Getting WebApi Exception Response in an Exception Filter

nr: #1 dodano: 2016-12-27 03:12

Try this var exceptionData = new ExceptionData { Name = "exception name", Message = "exception message" }; Content = new ObjectContent<ExceptionData>(exceptionData, JsonFormatter),

nr: #2 dodano: 2016-12-30 15:12

You just need to access the [System.Web.Http.HttpResponseException] from your context.Exception. In order to do that, and based on the picture, you need to right click on the [System.Web.Http.HttpResponseException] and add a watcher on it. That is going to give you the appropriate casting in order to retrieve the information from the context.

enter image description here

Source Show
◀ Wstecz