Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7074241
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:01:44+00:00 2026-05-28T06:01:44+00:00

I’m trying to do the equivalent of the dollowing C# 5 pseudocode:- async Task<int>

  • 0

I’m trying to do the equivalent of the dollowing C# 5 pseudocode:-

async Task<int> CallAndTranslate()
{
    try 
    {
        return await client.CallAsync();
    } catch(FaultException ex) {
        if (ex.FaultCode ...)
            throw new Exception("translated");
    }
}

Given an arbitrary Task which does not return a result, translating exceptions when backporting from C# 5 is easy using the technique supplied by @Drew Marsh

This technique doesn’t generalize trivially to Task<T> as any overload of Task.ContinueWith I can see returns a bald Task, not a Task<T>.

Is there a way to achieve this using the TPL APIs without having to resort to:

  • wrapping it in another Task<T>
  • causing the exception to go through the machinations of getting thrown and caught through the exception handling mechanisms
  • ADDED After intial answer…. should leave stack trace alone if exception is not to be translated

Here’s my naive placeholder implementation:

public class TranslatingExceptions
{
    Task<int> ApiAsync()
    {
        return Task<int>.Factory.StartNew( () => { 
           throw new Exception( "Argument Null" ); } );
    }

    public Task<int> WrapsApiAsync() 
    {
        return ApiAsync().TranslateExceptions(x=>{
            if (x.Message == "Argument Null" )
                throw new ArgumentNullException();
        });
    }

    [Fact]
    public void Works()
    {
        var exception = Record.Exception( () =>
            WrapsApiAsync().Wait() );
        Assert.IsType<ArgumentNullException>( exception.InnerException );
    }
}

The following Task<T> extension implements my placeholder implementation:

static class TaskExtensions
{
    public static Task<T> TranslateExceptions<T>( this Task<T> task, Action<Exception> translator )
    {
    // TODO REPLACE NAIVE IMPLEMENTATION HERE
        return Task<T>.Factory.StartNew( () =>
        {
            try
            {
                return task.Result;
            }
            catch ( AggregateException exception )
            {
                translator( exception.InnerException );
                throw;
            }
        } );
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:01:44+00:00Added an answer on May 28, 2026 at 6:01 am

    You can imitate await in .NET 4.0 using iterators ( yield ), but it’s not pretty.

    Without a state machine, you’re missing the whole point of await which is to return control to the caller until the work is complete and only then continue execution.

    Um, maybe I’ve missed the point! If you just want to use a ContinueWith<T> it’s just a slight tweak to the code from Drew Marsh:

    public Task<int> ApiAsync() // The inner layer exposes it exactly this way
    {
        return Task<int>.Factory.StartNew( () =>
            { throw new Exception( "Argument Null" ); } );
    }
    
    // this layer needs to expose it exactly this way
    public Task<int> WrapsApiAsync()
    {
        // Grab the task that performs the "original" work
        Task<int> apiAsyncTask = ApiAsync();
    
        // Hook a continuation to that task that will do the exception "translation"
        Task<int> result = apiAsyncTask.ContinueWith( antecedent =>
        {
            // Check if the antecedent faulted
            // If so check what the exception's message was
            if ( antecedent.IsFaulted )
            {
                if ( antecedent.Exception.InnerException.Message == "Argument Null" )
                {
                    throw new ArgumentNullException();
                }
    
                throw antecedent.Exception.InnerException;
            }
    
            return antecedent.Result;
        },
        TaskContinuationOptions.ExecuteSynchronously );
    
        // Now we return the continuation Task from the wrapper method
        // so that the caller of the wrapper method waits on that
        return result;
    }
    

    UPDATE: sample using TaskCompletionSource

    public static Task<int> WrapsApiAsync()
    {
        var tcs = new TaskCompletionSource<int>();
    
        Task<int> apiAsyncTask = ApiAsync();
    
        apiAsyncTask.ContinueWith( t =>
            {
                switch ( t.Status )
                {
                    case TaskStatus.RanToCompletion:
                        tcs.SetResult( task.Result );
                        break;
    
                    case TaskStatus.Canceled:
                        tcs.SetCanceled();
                        break;
    
                    case TaskStatus.Faulted:
    
                        if ( t.Exception.InnerException.Message == "Argument Null" )
                        {
                            try
                            {
                                throw new ArgumentNullException();
                            }
                            catch ( ArgumentNullException x )
                            {
                                tcs.SetException( x );
                            }
                        }
                        else
                        {
                            tcs.SetException( t.Exception.InnerException );
                        }
    
                        break;
                }
            }
        );
    
        return tcs.Task;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.