microsoft / dotnet

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
https://devblogs.microsoft.com/dotnet/
MIT License
14.25k stars 2.2k forks source link

System.InvalidCastException: Unable to cast object of type 'T' to type 'System.Threading.Tasks.Task`1[T] #1426

Open TacoTacoCode opened 5 months ago

TacoTacoCode commented 5 months ago

I have below method that throw InvalidCastException when jump into catch block on production. Do i need to do Task.FromResult for catch block now? Please help check

public async Task<T> foo(SomeRequest request, CancellationToken cancellationToken = default)
{
    try
    {
        var result = await bar(request, cancellationToken);
        if (result.Errors?.Count > 0)
        {
            return result;
        }

        if (!string.IsNullOrEmpty(result.ContentLocationUri))
        {
            await DeleteFileAsync(new WebDavRequest()
            {
                FileName = result.ContentLocationUri
            }, cancellationToken);
        }

        return result;
    }
    catch (Exception exception)
    {
        return new T
        {
            Errors = new List<string>()
            {
                exception.Message
            }
        };
    }
}

.NET SDK: Version: 8.0.100 Commit: 57efcf1350 Workload version: 8.0.100-manifests.6c33ef20

Runtime Environment: OS Name: Windows OS Version: 10.0.17763 OS Platform: Windows RID: win-x64

.NET workloads installed: Workload version: 8.0.100-manifests.6c33ef20

Host: Version: 8.0.0 Architecture: x64 Commit: 5535e31a71

WeihanLi commented 5 months ago

Is there a sample code to repro? And suggest to move this issue to dotnet/runtime https://github.com/dotnet/runtime/issues

GibbOne commented 5 months ago

Yes, you need Task.FromResult between return and new T.

Something like:

    catch (Exception exception)
    {
        return Task.FromResult(new T
        {
            Errors = new List<string>()
            {
                exception.Message
            }
        });
    }