对 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);
}
}
我认为它的缺点是
- 根本不会向用户返回任何错误消息。
StatusCodeResult
不提供任何重载来提供消息 - 您的函数的所有执行都将显示为成功,例如在 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/