Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'Catch exception' extension on Task class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading