问题描述
我用HTTP触发器创建了一个Azure函数.我希望将详细的错误信息返回给调用者.有没有办法解决未捕获的异常?奇怪的是,Azure Functions在Visual Studio中运行时会返回详细的错误信息,但在部署时却不会返回.
I've created an Azure Function with an HTTP trigger. I would like detailed error information to be returned to callers. Is there a way of doing for uncaught exceptions? Strangely, Azure Functions does return the detailed error info when running in Visual Studio, but not when deployed.
[FunctionName("MyAzureFunction")]
public static async Task<HttpResponseMessage> RunAsync(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage httpRequest,
TraceWriter traceWriter,
CancellationToken cancellationToken)
{
try
{
var response = await ProcessAsync(request, cancellationToken);
return httpRequest.CreateResponse(HttpStatusCode.OK, response);
}
catch (ArgumentException ex)
{
traceWriter.LogWarning($"Argument error: {ex}");
return httpRequest.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
catch (Exception ex)
{
traceWriter.LogError($"Error: {ex}");
throw;
}
}
推荐答案
通常,从安全角度来看,将异常详细信息返回给外部调用者被认为是不好的做法.因此,默认情况下可以屏蔽此信息.
Generally, returning exception details to the external caller is considered bad practice from security standpoint and otherwise. Because of that, it makes sense to block this information by default.
我将throw;
语句替换为返回手动格式化错误的语句.如果您可以将异常消息公开给调用者,那么就很简单
I would replace throw;
statement with the one returning manually formatted error. If you are OK with exposing the exception message to the caller, it's as simple as
return httpRequest.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
如果调用方是外部的,我也不会这样做:相反,返回一般错误消息,然后依靠日志进行调试.
If the caller is external, again, I would not do that: instead, return a generic error message and then rely on logging for debugging.
这篇关于从Azure函数HttpTrigger返回错误详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!