Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch custom exceptions from an async method

Tags:

c#

.net

I'm trying to catch a custom exception thrown inside an async method but for some reason it always ends up being caught by the generic exception catch block. See sample code 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)
    {
    }
}
like image 412
sloppy Avatar asked Apr 24 '17 07:04

sloppy


People also ask

How do I get async exception?

To catch an exception that an async task throws, place the await expression in a try block, and catch the exception in a catch block. Uncomment the throw new Exception line in the example to demonstrate exception handling. The task's IsFaulted property is set to True , the task's Exception.

What happens if an exception is thrown within an asynchronous method?

As we know, in asynchronous programming, control does not wait for the function's result and it executes the next line. So when the function throws an exception, at that moment the program control is out of the try-catch block.

Can async methods declare out parameters?

You can't have async methods with ref or out parameters.

How do you catch errors with await?

The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.


1 Answers

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
}
like image 157
Patrick Hofman Avatar answered Oct 20 '22 05:10

Patrick Hofman