1

I have an async action, actually from ASP.net Identity, which is throwing an exception in an async database query. However this exception does not seem to be making it to the general application_error I have in place in Global.asax.cs. Other exceptions are being caught correctly.

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(model.UserName.Trim(), model.Password.Trim());
            ...
        }
    }

In my case the database had been changed without updating the models - but I would really like a mechanism which I can apply globally to all the various async actions I have.

I did see another post which suggested hooking into the unobserved exception on the task scheduler like so:

        TaskScheduler.UnobservedTaskException += (sender, e) =>
        {
            Console.WriteLine("Saving the day! This exception would have been unobserved: {0}",
                              e.Exception);
            e.SetObserved();
        };

However break points inside the lambda are never hit. I can intercept the exception with a try/catch block around the async but that is highly explicit and a pain to implement everywhere.

How can I catch and, at the least, log these exceptions?

noseratio
  • 59,932
  • 34
  • 208
  • 486
stimms
  • 42,945
  • 30
  • 96
  • 149

2 Answers2

0

Either use or create a logging table for the exceptions and when there's an error in your call, log the exception. This would also allow you to then make a synchronous call to your logging table, see if you have any exceptions from your asynchronous calls, retrieve them, and include them into your usual error handling process. Wrap them in an ExceptionManager or an entity like that, and call it if something errors out in your Global.asax.cs file to make sure you're reporting all of the errors.

gfish3000
  • 1,557
  • 1
  • 11
  • 22
  • 1
    That seems like a pretty localized fix which would require me to wrap all async calls. – stimms Apr 09 '14 at 18:16
  • Not if you wrap your actual call to the database itself through a facade in a `try/catch` block or include exception handling as a part of your repository's work with objects. – gfish3000 Apr 09 '14 at 18:45
0

There's a good reason behind such exception observation and handling behavior, I've described it here.

If you like to log exceptions as they occur inside async methods, without extra wrapping code, I can only think of "How to: Receive First-Chance Exception Notifications".

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486