I need to translate an exception emanating from a Task<T>
in the same manner that doing the following would for normal synchronous code:
try {
client.Call();
} catch(FaultException ex) {
if (ex.<Some check>)
throw new Exception("translated");
}
However, I want to do this asynchronously, i.e., Call
above is actually Task CallAsync()
.
So in C# 5 my method would look like this:
async Task CallAndTranslate()
{
try{
await client.CallAsync();
} catch(FaultException ex) {
if (ex.FaultCode ...)
throw new Exception("translated");
}
}
But I'm using C# 4 for now.
So what can I do given that I want to trigger a Task but have the (TPL) Fault be translated and then expose the whole thing once again as a Task<T>
?
- originally emanating from a WCF webservice but that's not important here
EDIT: A slightly more concrete way of saying it:
public class TranslatingExceptions
{
public Task ApiAsync() // The inner layer exposes it exactly this way
{
return Task.Factory.StartNew(()=>{ throw new Exception( "Argument Null" );});
}
public Task WrapsApiAsync() // this layer needs to expose it exactly this way
{
// async preview pseudocode for what I need to do
try {
await ApiAsync( );
} catch (Exception exception){
if( exception.Message == "Argument Null" )
throw new ArgumentNullException();
}
}
[Fact]
public void Works()
{
var exception = Record.Exception( () =>
WrapsApiAsync().Wait());
Assert.IsType<ArgumentNullException>( exception.InnerException);
}
}
How would you implement WrapsApiAsync()
without needing C# 5?
Ok, so now that I'm entirely clear on what you're looking for, here's all you would need to do to build the equivalent in 4.0:
This should accomplish what you're looking for. One thing to note is that I use
TaskContinuationOptions.ExecuteSynchronously
when creating the continuation. This is because this work is small and tight and you don't want to incur the over head of waiting for a whole other thread having to be picked up from the thread pool by the scheduler just to do this check.