Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TacoTacoCode opened this issue Jan 25, 2024 · 2 comments

Comments

@TacoTacoCode
Copy link

TacoTacoCode commented Jan 25, 2024

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
Copy link

WeihanLi commented Jan 25, 2024

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

@GibbOne
Copy link

GibbOne commented Jan 26, 2024

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
            }
        });
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants