如何使用ASP.net MVC的AsyncController处理异常?

时间:2011-05-30 00:06:50

标签: asp.net-mvc-3 exception-handling asynchronous

我有这个......

    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();
    }

有没有更好的方法将异常传回ASP.net?

干杯,伊恩。

2 个答案:

答案 0 :(得分:5)

Task将为您捕获例外情况。如果你调用task.Wait(),它将在AggregateException中包装任何捕获的异常并抛出它。

[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();
}

简单地添加[HandleError]属性是不够的。由于异常发生在另一个线程中,我们必须将异常返回到ASP.NET线程,以便对它执行任何操作。只有在我们从正确的位置抛出异常之后,[HandleError]属性才能完成其工作。

答案 1 :(得分:0)

尝试在FooAsync操作中添加这样的属性:

[HandleError (ExceptionType = typeof (MyExceptionType) View = "Exceptions/MyViewException")]

这样您就可以创建一个视图来向用户显示详细错误。