2011-05-30 60 views
7

我有了这个...如何用ASP.net MVC的AsyncController处理异常?

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的更好的办法?

干杯,伊恩。

回答

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")] 

这种方式,你可以创建一个视图来显示详细的错误给用户。