简体   繁体   中英

HTTP trigger does not return stacktrace in Azure Functions v2

Consider a simple HTTP trigger that throws an exception. When I make a call to this trigger via Postman, it return a 500 Internal Server Error, but the body is empty. As a developer, I want to see the stacktrace so that I can quickly debug what's going on.

// Azure Functions v2
[FunctionName("HttpTrigger2")]
public static async Task<HttpResponseMessage> HttpTrigger2(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req)
{
    throw new System.Exception("I want to be in the response body.");
}

This is run locally. I have not yet tested this remotely.

I believe Azure Functions v1 did show the stacktrace.

I know that there are various ways of inspecting the logs, eg by hooking up the environment to AppInsights. What I am looking for an immediate response from the server.

It should be by design that v2 function doesn't return stack trace anymore like v1 does. And on remote Azure site, neither v1 nor v2 function returns stack trace. The design is reasonable, stack trace is used for debug while the response body is apparently not. With stack trace returned as response, we seem to expose lengthy and sometimes private info.

If we want to get exceptions as response for convenience while debugging locally, catch the exception and return it as response.

To work with HttpRequestMessage

        try
        {
            throw new System.Exception("I want to be in the response body.");
        }
        catch (Exception exception)
        {
            log.LogError(exception, exception.Message);
            return req.CreateResponse(HttpStatusCode.InternalServerError, exception);
        }

In v2, we also could use HttpRequest and the response type should be IActionResult .

        try
        {
            throw new System.Exception("I want to be in the response body.");
        }
        catch(Exception exception)
        {
            log.LogError(exception, exception.Message);
            var res = new ObjectResult(exception)
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };
            return res;
        }

You can also add the env variable CLI_DEBUG to 1 in your machine to get full exceptions in local env, debugging etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM