0

I have a custom exception InsertLeadException which inherts from Exception. Now, I have the code like:

....
try
{
    isSuccess = _proxy.SendAsync(message).NoState();
}
catch (InsertLeadException ex)
{
    ...
}
catch (Exception ex)
{
    ...
}   
....

Here is SendAsync in proxy:

public async Task<bool> SendAsync(Message message)
{
    List<Task<bool>> tasks = new List<Task<bool>>();
    var task = ProcessMessageAsync(message);
    tasks.Add(task);

    var legacyTask = LogLeadAsync();
    tasks.Add(legacyTask);

    Task.WaitAll(tasks.ToArray());

    return task.Result;     // only need return result of 1st task
}

In the ProcessMessageAsync, I simply does

throw new InsertLeadException("Test Exception."); 

And in LogLeadAsync, there is no exception.

When run the code, for some reasons, it does not catch InsertLeadException, instead, it catches Exception.

But, if I implement like below, it does catch the InsertLeadException:

public async Task<bool> SendAsync(Message message)
{
    var task = await ProcessMessageAsync(message).NoState();        
    var legacyTask = await LogLeadAsync().NoState();

    return task;        
}

Anyone knows why?

Thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91
  • .NoState(); what does that do? also if you want exceptions to be caught, you should await/wait() them (idk if that happens now because of noState) – sommmen May 22 '20 at 22:07
  • 1
    Because you are not awaiting in your `isSuccess = _proxy.SendAsync(message).NoState();` line. – Guru Stron May 22 '20 at 22:14
  • .NoState is an extension which is for await – urlreader May 22 '20 at 22:39
  • Avoid using `Wait()`, `Result` and `WaitAll` on tasks as these can lead to deadlocks and exceptions get wrapped in an AggregateException. The last two lines of SendAsync should be `await Task.WhenAll(tasks.ToArray()); return await task;`. – ckuri May 22 '20 at 23:02

0 Answers0