aliyun / aliyun-oss-csharp-sdk

Aliyun OSS SDK for C#
MIT License
384 stars 206 forks source link

No exception is thrown when internet is down using OssClient.BeginPutObject and OssClient.BeginGetObject #130

Open ronan-soo opened 3 years ago

ronan-soo commented 3 years ago

the following my code is my asynchronous method for Upload.

When there is no internet service, the OssClient doesnt throw any exception. This issue happens because the client implementation only IAsyncResult.Complete() to pass the successful result, but didn't pass the exception. Because the exception happens in Task.ContinueWIth(), hence it is unable to catch this exception on caller thread.

In this case, I gonna post a fix for this in "sdk\Common\Communication\netcore\ServiceClientNewImpl.cs".


        public async Task UploadAsync(string bucketName, string blobName, Stream content, string downloadFileName)
        {
            var client = GetOssClient();

            // AliCloud OSS will auto append "Content-Type" header
            // AliCloud OSS need to append "Content-Disposition" header upon uploading
            var metadata = new ObjectMetadata();
            if (!string.IsNullOrEmpty(downloadFileName)) metadata.AddHeader("Content-Disposition", $"attachment; filename=\"{downloadFileName}\"");

            var tcs = new TaskCompletionSource<PutObjectResult>();

            AsyncCallback putObjectCallback = (IAsyncResult iar) =>
            {
                try
                {
                    var result = client.EndPutObject(iar);

                    if (result.HttpStatusCode == HttpStatusCode.OK)
                    {
                        tcs.TrySetResult(result);
                    }
                    else
                    { 
                        throw new InvalidOperationException("Upload fail.");
                    }
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            };

            client.BeginPutObject($"{_options.BucketNamePrefix}-{bucketName}", blobName, content, metadata, putObjectCallback, null);

            await tcs.Task;
        }
`