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

7

我有这个问题,一直在尝试解决。

    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?
谢谢,Ian。
2个回答

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]属性才能发挥作用。


0

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接