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

吃可爱长大的小学妹 提交于 2020-01-02 03:13:53

问题


I've got this...

    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 of passing an exception back to ASP.net?

Cheers, Ian.


回答1:


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

Simply adding a [HandleError] attribute isn't good enough. Since the exception occurs in a different thread, we have to get the exception back to the ASP.NET thread in order to do anything with it. Only after we have the exception thrown from the right place will the [HandleError] attribute be able to do its job.




回答2:


Try putting an attribute like this in FooAsync action:

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

This way you can create a view to display the detailed error to the user.



来源:https://stackoverflow.com/questions/6171273/how-do-you-handle-an-exception-with-asp-net-mvcs-asynccontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!