I am trying to implement a common method to handle all API call asynchronously and handle the exception. How can I get the exception inside the Task.Run() to be passed on to the main thread, so that I can handle it globally in unhandled exceptions.
Below is my global handler,
AppDomain.CurrentDomain.UnhandledException += LogUnhandledCurrentDomainException;
Dispatcher.UnhandledException += OnDispatcherUnhandledException;
Below is my Async code to call the API using Task.Run()
public async Task<T> InvokeApiAsync<T>(Func<T> function)
{
return await Task.Run(function);
}
Can anyone suggest how I can pass the exception from inside Task.Run() to the main thread.
I am calling the Async function from my WPF View model, using the below method,
private async Task LoadDocuments()
{
IsBusy = true;
Documents = await _serviceInvoker.InvokeApiAsync(() => _blobService.GetBlobs().ToList());
IsBusy = false;
}
The above method is called from Caliburn.Micro event,
protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
{
await LoadDocuments();
await base.OnInitializeAsync(cancellationToken);
}