1

I've a problem with ASP.NET MVC controller and async operation on EF context. If a problem occurs (an exception) on entityContext, I can't see/capture/debug the exception, the execution returns immediatly on asp.net pipeline and (in my case) I see the 500.html page. This is the code where I do not have any control:

RENEWAL renewal;
using (var db = new MyEntities()) //Breakpoint #1
{
    try
    {
        renewal = await db.RENEWAL.FindAsync(id, ctr);
    }
    catch (AggregateException ex)
    { //breakpoint #2
        throw;
    }
    return View(renewal); //Breakpoint #3
}

I can debug with Breakpoint #1, and on "FindAsync" operation there is an error but, both Breakpoint #2 and #3 are never reached.

So, I've modified the code like this:

RENEWAL renewal;
using (var db = new MyEntities())
{
    try
    {
        renewal = await db.RENEWAL.FindAsync(id, ctr)
                          .ContinueWith(t =>
                           {
                               Debug.Print("Continue With");
                               return t.Result; //breakpoint #2
                           });
    }
    catch (AggregateException ex)
    { //breakpoint #3
        throw;
    }
    return View(renewal); //Breakpoint #4
}

Now Breakpoints #2 and #3 are working.

I didn't quite understand how async / await works in an MVC controller. Can you tell me the difference between the first and the second block, and if there is a correct way to manage these operations towards EF from controller? Thanks

Glauco Cucchiar
  • 764
  • 5
  • 19
  • 1
    `await` doesn't throw AggregateException, it returns the actual exception that was raised inside a task or async operation. Use `Exception` instead – Panagiotis Kanavos Feb 27 '20 at 16:05

1 Answers1

2

because exception type desn't match 'AggregateException' anymore, you should catch base 'Exception' and check its type.

Mehrdad
  • 1,523
  • 9
  • 23
  • and, when can I use AggregateException? I remember badly – Glauco Cucchiar Feb 27 '20 at 16:48
  • 1
    AggregateException is for your situation, may be something changed. i found [this](https://stackoverflow.com/questions/12007781/why-doesnt-await-on-task-whenall-throw-an-aggregateexception) – Mehrdad Feb 27 '20 at 17:02