Search code examples
asp.net-mvc-3timeoutexceptionasynccontroller

Best way of handling timeouts with AsyncController


I have a long time polling controller in my MVC3 project. It has its timeout set to 30 seconds. I have a HandleErrorAttribute implementation that handles logging of all errors.

Since the timout throws a TimeoutException it means these will be presented in the log.

I need to intercept this error before my HandleErrorAttribute class gets it and return a json object instead of the 500 error page. Whats the best approach for this?

I did this and it works

public class HandleTimeout : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception is TimeoutException)
        {
            filterContext.Result = new { Timeout = true }.AsJson();
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 200;
        }

        base.OnException(filterContext);
    }
}

Best approach?


Solution

  • I went with this route, the difference from my above code is that I also check if the Controller is Async, because we only want to handle Timeouts in this fashion if we are in a long time polling scenarios.

    public class HandleTimeout : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if(filterContext.Exception is TimeoutException && filterContext.Controller is AsyncController)
            {
                filterContext.HttpContext.Response.StatusCode = 200;
                filterContext.Result = new { Timeout = true }.AsJson();
                filterContext.ExceptionHandled = true;
            }
    
            base.OnException(filterContext);
        }
    }