Skip to content

Improve Stack Trace for InnerException of TargetInvocationExceptions #1613

@FabianNitsche

Description

@FabianNitsche

During equivalency steps, methods are called by reflection e.g.

try
{
    HandleMethod.MakeGenericMethod(typeOfEnumeration).Invoke(null, new[] { validator, subjectAsArray, comparands.Expectation });
}
catch (TargetInvocationException e)
{
    throw e.Unwrap();
}

The Unwrap extension method gets the inner exception from the TargetInvocationException. However, the throw in the catch kills the original stack trace which lead to some confusion when trying to understand the problem.

Since FluentAssertions 6.0.0 is dropping support for Framework <= 4.5 it could now use ExceptionDispatchInfo to keep the original stack trace.

The Unwrap extension method then would change to

public static ExceptionDispatchInfo Unwrap(this TargetInvocationException exception)
{
    Exception result = exception;
    while (result is TargetInvocationException)
    {
        result = result.InnerException;
    }

    return ExceptionDispatchInfo.Capture(result);
}

And the site of the invocation would change to

catch (TargetInvocationException e)
{
    e.Unwrap().Throw();
}

If you are interested in this improvement, I can provide a pull request draft.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions