How do you handle an exception with ASP.net MVC

2019-04-26 18:32发布

问题:

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.