2

I have code that catches all exceptions that are thrown by a server call as follows:

    new public Task SaveAsync()
    {
        return ServerException.Wrap(base.SaveAsync);
    }

Where ServerException.Wrap looks like:

    public static async Task<T> Wrap<T>(Func<Task<T>> func)
    {
        try
        {
            return await func();
        }
        catch (Exception ex)
        {
            // This is an internal error that shouldn't happen.
            throw new ServerException(ex);
        }
    }

    public static async Task Wrap(Func<Task> func)
    {
        await Wrap(async () =>
            {
                await func();
                return true;
            });
    }

And then I have a function that calls SaveAsync as follows:

        try
        {
            await problem.SaveAsync();
        }
        catch (ServerException ex)
        {
            Logger.LogException("Error saving problem.", ex);
        }

I have some internal error that generates an exception which I catch in the above line and then it gets logged as follows:

2015-10-20 11:20:44.502 [Line 99] Error saving problem. (Exception: Exceptions.ServerException: ---> System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException (ExceptionResource resource) [0x00000] in /Users/builder/data/lanes/1977/2c66d2fe/source/mono/external/referencesource/mscorlib/system/throwhelper.cs:74

However a few seconds later I get an unhanded exception warning that gets logged:

2015-10-20 11:21:16.352 Warning: Unhandled exception: System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException (ExceptionResource resource) [0x00000] in /Users/builder/data/lanes/1977/2c66d2fe/source/mono/external/referencesource/mscorlib/system/throwhelper.cs:74

Why do I get the second unobserved exception, even though I am catching and handling the first exception? This exception seems to be thrown by my ServerException.Wrap method.

I am using MonoTouch.

Kostub Deshmukh
  • 2,852
  • 2
  • 25
  • 35

1 Answers1

-2

You need to explicitly set the exception to observed.

For that, you need to subscribe to the TaskScheduler's UnobservedTaskException event, and set it explicitly to observed (call SetObserved() on it).

See here:

UnobservedTaskException being throw...

EDIT: Of course, you can also just catch AggregateException as well, or use ContinueWith() to observe and resume the task.

See the bottom of the official documentation:

Exception Handling (MSDN)

Community
  • 1
  • 1