Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaited task does not handle exception gracefully

I expected that I could use this pattern:

var task = Task.Run(() => Agent.GetUserType(Instance));
await task;
string information = task.GetExceptionOrStatus(); // extension method

When my sql server is not started - just as a testcase - I see that the exception that the WCF service throws, is not handled gracefully by the task, I get:
An exception of type 'System.ServiceModel.FaultException' occurred in Microsoft.Threading.Tasks.dll but was not handled in user code.
I was under the impression that my code would be able to extract the error from the task object.

How should I do it better?

like image 895
Gerard Avatar asked Feb 04 '26 23:02

Gerard


2 Answers

await will propagate any exceptions on that task, by design.

var task = Task.Run(() => Agent.GetUserType(Instance));
try
{
  await task;
}
catch (Exception ex)
{
  // TODO
}
string information = task.GetExceptionOrStatus(); // extension method
like image 186
Stephen Cleary Avatar answered Feb 07 '26 15:02

Stephen Cleary


If you don't want await to throw, you could create a new Task based on the previous Task, that never fails. Something like:

static async Task<T> IgnoreException<T>(this Task<T> task)
{
    try
    {
        return await task;
    }
    catch
    {
        return default(T);
    }
}

Alternative implementation:

static Task<T> IgnoreException<T>(this Task<T> task)
{
    return task.ContinueWith(t => t.Exception == null ? t.Result : default(T));
}

Usage then would look like this:

await task.IgnoreException();
string information = task.GetExceptionOrStatus(); // extension method
like image 42
svick Avatar answered Feb 07 '26 14:02

svick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!