David Gard
David Gard

Reputation: 12047

AggregatedException - Access properties of inner exception where type extends exception

I have a method which catches AggregateException's. However, I can't seem to access properties on the inner exceptions that were added to exceptions that inherit the base Exception.

For example, the type Azure.RequestFailedException contains a property ErrorCode. Using the code below, I am not able to access that property when handling an AggregatedException because ex is always of type Exception.

Console.WriteLine(ex.ErrorCode);

'Exception' does not contain a definition for 'ErrorCode'...

How can I access these properties when the exception is part of an AggregatedException?

public Response GetBin(string binName)
{
    try
    {
        BlobContainerClient container = this._storage.GetContainer(binName);
        Azure.AsyncPageable<BlobItem> blobs = this._storage.GetBlobs(container);
        return new GetBinResponse(container, blobs);
    }
    catch (AggregateException ae)
    {
        Response exResponse = null;
        ae.Handle(ex =>
        {
            if (ex is Azure.RequestFailedException)
            {
                Console.WriteLine(ex.ErrorCode);
                exResponse = new BinNotFoundExceptionResponse(binName);
                return true;
            }
            else
            {
                exResponse = new BadRequestResponse(ex.Message);
                return true;
            }
        });
        return exResponse;
    }
    catch (Exception ex)
    {
        return new BadRequestResponse(ex.Message);
    }
}

Upvotes: 0

Views: 258

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You do not convert to but only check for the type. Use this instead:

if (ex is Azure.RequestFailedException e)
{
    Console.WriteLine(e.ErrorCode)
}

Or before pattern-matching, which was introduced in C#7:

var e = ex as Azure.RequestFailedException;
if (e != null)
{
    Console.WriteLine(e.ErrorCode)
}

Upvotes: 2

Related Questions