Home > Enterprise >  'Catch exception' extension on Task class
'Catch exception' extension on Task class

Time:08-30

I have code like this:

try { await myFunc(); }
catch (MyException ex) 
{
    switch (ex.Code)
    {
        case 1: ... break;
        case 2: ... break;
        ...
    }
}

And was wondering is it possible to make all that look something like this:

...
{
    await myFunc().HandleMyExeptions(OnMyException);
}

private void OnMyException(int exCode)
{
    switch (ex.Code)
    {
        case 1: ... break;
        case 2: ... break;
        ...
    }
}

where I would create extension class for tasks something like this

public static class TaskExtensions
{
    public static void HandleErrors(this Task task, Action<int> handleError)
    {
        // I don't know what would go here nor whether the header of 
        // this function is a step in a good direction
    }
}

CodePudding user response:

It's going to look something like this:

public static Task HandleErrors(this Task task, Action<int> handleError) =>
    task.ContinueWith(t =>
    {
        if (t.Status == TaskStatus.Faulted && t.Exception.InnerException is MyException ex)
        {
            handleError(ex.Code);
        }
    });

Had you provided sample code in your question that showed how your existing exception handling worked, then I would have fully tested this, but you didn't. If you care to write that code and add it to your question, then I'll do the testing.


A simpler approach using await:

public static async Task HandleErrors(this Task task, Action<int> handleError)
{
    try
    {
        await task;
    }
    catch (MyException ex)
    {
        handleError(ex.Code);
    }
}
  • Related