【问题标题】:How do you handle an exception with ASP.net MVC's AsyncController?您如何使用 ASP.net MVC 的 AsyncController 处理异常?
【发布时间】:2011-05-30 00:06:50
【问题描述】:

我有这个...

    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?

干杯,伊恩。

【问题讨论】:

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


    【解决方案1】:

    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] 属性才能完成它的工作。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2012-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-20
        • 2012-05-04
        • 2012-09-17
        • 2019-03-01
        相关资源
        最近更新 更多