简体   繁体   中英

'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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM