Fix custom exceptions to async method

I am trying to catch a custom exception that is thrown inside the async method, but for some reason it always ends up in a common catch catch block. See code example below.

class Program { static void Main(string[] args) { try { var t = Task.Run(TestAsync); t.Wait(); } catch(CustomException) { throw; } catch (Exception) { //handle exception here } } static async Task TestAsync() { throw new CustomException("custom error message"); } } class CustomException : Exception { public CustomException() { } public CustomException(string message) : base(message) { } public CustomException(string message, Exception innerException) : base(message, innerException) { } protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context) { } } 
+5
source share
1 answer

The problem is that Wait throws an AggregateException , not the exception you are trying to catch.

You can use this:

 try { var t = Task.Run(TestAsync); t.Wait(); } catch (AggregateException ex) when (ex.InnerException is CustomException) { throw; } catch (Exception) { //handle exception here } 
+6
source

Source: https://habr.com/ru/post/1267081/


All Articles