Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle an exception with ASP.net MVC's AsyncController?

I've got this...

    public void FooAsync()
    {
        AsyncManager.OutstandingOperations.Increment();

        Task.Factory.StartNew(() =>
        {
            try
            {
                doSomething.Start();
            }
            catch (Exception e)
            {
                AsyncManager.Parameters["exc"] = e;
            }
            finally
            {
                AsyncManager.OutstandingOperations.Decrement();
            }
        });
    }

    public ActionResult FooCompleted(Exception exc)
    {
        if (exc != null)
        {
            throw exc;
        }

        return View();
    }

Is there a better way of passing an exception back to ASP.net?

Cheers, Ian.

like image 776
Ian Warburton Avatar asked May 30 '11 00:05

Ian Warburton


1 Answers

Task will catch the exceptions for you. If you call task.Wait(), it will wrap any caught exceptions in an AggregateException and throw it.

[HandleError]
public void FooAsync()
{
    AsyncManager.OutstandingOperations.Increment();
    AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
    {
        try
        {
            DoSomething();
        }
        // no "catch" block.  "Task" takes care of this for us.
        finally
        {
            AsyncManager.OutstandingOperations.Decrement();
        }
    });
}

public ActionResult FooCompleted(Task task)
{
    // Exception will be re-thrown here...
    task.Wait();

    return View();
}

Simply adding a [HandleError] attribute isn't good enough. Since the exception occurs in a different thread, we have to get the exception back to the ASP.NET thread in order to do anything with it. Only after we have the exception thrown from the right place will the [HandleError] attribute be able to do its job.

like image 105
Daniel Schilling Avatar answered Oct 03 '22 12:10

Daniel Schilling