我有一个Azure函数HTTP触发的函数,该函数写入可能以重复条目结尾的Azure表。我注意到,即使我尝试/捕获了整个函数,仍然会向函数运行器“泄漏”一个异常,从而返回HTTP500。是否有任何方法可以捕获这种异常?
下面是代码的缩小版本:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
namespace FunctionTest
{
public class Entry
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
}
public static class Debug
{
[FunctionName("Debug")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
HttpRequest req,
[Table("Debug")]
IAsyncCollector<Entry> tableBinding,
ILogger log)
{
try
{
await tableBinding.AddAsync(new Entry()
{
PartitionKey = "1111",
RowKey = "1111",
});
await tableBinding.FlushAsync();
}
catch (StorageException)
{
// we expect an Exception "The specified entity already exists"
return new OkObjectResult("This passes test");
}
return new OkObjectResult("This passes test too");
}
}
}
代码是在Azure Function运行时2.0(.NET Core之一)下编写的。
触发/api/debug
两次或更多次,您将看到:
catch{}
代码,但仍返回HTTP 500(!)答案 0 :(得分:2)
我猜想,使用IAsyncCollector<>
会破坏这里的内容。如果要避免此类问题,请尝试交换以下绑定:
[Table("Debug")] IAsyncCollector<Entry> tableBinding
收件人:
[Table("Debug")] CloudTable tableBinding
然后,使用以下代码段代替使用tableBinding.AddAsync()
:
var op = TableOperation.Insert(new Entry());
await tableBinding.ExecuteAsync(op);
使用这种方法,您应该能够捕获异常,而不会将其泄漏到Function运行时。
答案 1 :(得分:-1)
您的try / catch块应如下所示,以捕获所有错误
try
{
}
catch (StorageException)
{
return new OkObjectResult("This passes test");
}
catch (Exception ex)
{
// return different error code
}