c# - HTTP 触发函数的正确错误处理?

标签 c# azure .net-core azure-functions

对 HTTP 触发的 Azure Functions v2 进行错误处理的正确方法是什么?应该 - 正如本文中的建议 answer - 所有内部异常都被捕获并且没有任何异常被抛出?

即始终用 try-catch 包围您在函数内所做的所有操作,如下所示:

[FunctionName("DemoHttpFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
    try
    {
        await InnerDoSomething();
        return new NoContentResult();
    }
    catch(Exception ex)
    {
        log.LogError(ex, "Something went wrong");
        return new StatusCodeResult(500);
    }
}   

我认为它的缺点是

  1. 根本不会向用户返回任何错误消息。 StatusCodeResult 不提供任何重载来提供消息
  2. 您的函数的所有执行都将显示为成功,例如在 Application Insights 的日志记录中。

最佳答案

No error message at all gets returned to the user. StatusCodeResult does not provide any overload to supply a message

您可以控制代码。您可以轻松使用包含所需信息的不同结果。

//...

catch(Exception ex)
{
    log.LogError(ex, "Something went wrong");
    var model = new { error = "User friendly something went wrong" };
    return new ObjectResult(model) {
        StatusCode = 500
    };
}

//...

关于c# - HTTP 触发函数的正确错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855518/

相关文章:

c# XML Treeview (Plumbing) 收藏

C# - ActiveX .DrawToBitmap 等效项

c# - Azure负载测试: Spin up multiple instances runtime

python - 有没有办法在 Azure Functions 中延迟 QueueMessage?

entity-framework - 相当于 Entity Framework Core 1 (EF7) 中的 .HasOptional

c# - 从数据库表创建枚举/类

c# - XML 序列化以将请求发送到 SOAP 服务 C#

image - 如何上传带有描述和标题等元数据的图像

python - 分页异步迭代器协议(protocol)不可用(适用于 Python 的 Azure SDK)

c# - 如何移动调试指针以更改 Visual Studio Code Debugger 中的执行流程