我正在遵循此 Google 的教程,但它在
operation.PollUntilCompleted()
操作中失败。
我收到的例外是
'operation.Result' threw an exception of type 'System.InvalidOperationException' Google.Cloud.Retail.V2.SetInventoryResponse {System.InvalidOperationException}
带有错误消息
"Operation has not completed."
这是我从教程中执行的代码。为了方便我把它留在这里:
/// <summary>
/// Call the Retail API to set product inventory.
/// </summary>
/// <param name="product">The actual product.</param>
public static void SetProductInventory(string productName)
{
var setInventoryRequest = GetSetInventoryRequest(productName);
var client = ProductServiceClient.Create();
var operation = client.SetInventory(setInventoryRequest);
Console.WriteLine("Set inventory. Please, wait.");
Console.WriteLine();
operation.PollUntilCompleted(); // <<<<< This line causes the exception.
}
}
/// <summary>
/// The set inventory tutorial class.
/// </summary>
public static class SetInventoryTutorial
{
[Runner.Attributes.Example]
public static void PerformSetInventoryOperation()
{
string projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
// Create product.
Product createdProduct = CreateProductSample.CreateRetailProductWithFulfillment(projectId);
// Set inventory for product.
SetInventorySample.SetProductInventory(createdProduct.Name);
// Get product.
Product product = GetProductSample.GetRetailProduct(createdProduct.Name);
Console.WriteLine($"Product Price Info: {product.PriceInfo}");
Console.WriteLine();
// Delete product.
DeleteProductSample.DeleteRetailProduct(createdProduct.Name);
}
我可以成功创建产品。当我尝试设置库存时,它在
operation.PollUntilCompleted()
行抛出异常。
您能告诉我如何进行吗? 预先感谢您。
---更新---
这里是存储库,其中包含一个示例应用程序,可重现相同异常的堆栈跟踪。
我尝试了另一种方法,
AddLocalInventoriesAsync
,它抛出了相同的错误消息。
在评论中反复讨论后,发现代码本身没有抛出异常。相反,仅在检查不完整操作的
Result
属性时,才会在调试器中看到异常。这与 documented 完全相同 - 当操作尚未完成时,尝试访问其 Result
属性会抛出 InvalidOperationException
。
操作完成后查看结果的最简单方法是使用
PollUntilCompleted
的返回值:
operation = operation.PollUntilCompleted();
此语句完成后,在调试器中检查
operation
应显示结果。
一般来说,我建议不要担心“仅”在调试器中检查属性时显示的异常 - 除非您的代码评估相同的属性,否则您不会遇到该异常。