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

I have it...

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 to pass an exception to ASP.net?

Greetings, Jan.

+7
source share
2 answers

Task will catch exceptions for you. If you call task.Wait() , it will wrap all detected 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(); } 

Just adding the [HandleError] attribute is not enough. Since the exception occurs in another thread, we must return the exception to the ASP.NET thread in order to do something with it. Only after we eliminate the exception from the right place, the [HandleError] attribute will be able to do its job.

+5
source

Try putting an attribute like this in your FooAsync action:

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

In this way, you can create a view to display a detailed error for the user.

0
source

All Articles