azure-functions-dotnet-worker: Exception handling middleware example not behaving as expected

I have copied the exception handling sample from here https://github.com/Azure/azure-functions-dotnet-worker/blob/main/samples/CustomMiddleware/ExceptionHandlingMiddleware.cs however the result I get it not as I would expect. I am getting the whole HttpResponse object back as json in the body of the response. The actual data I pass in to WriteAsJsonAsync is appearing Base64 encoded in the body property of the response. Also the response code is always 200, rather than the value I set.

e.g. I am seeing the body of response as follows:

{
  "method": "",
  "query": {},
  "statusCode": "400",
  "headers": {
    "Content-Type": "application/json; charset=utf-8"
  },
  "enableContentNegotiation": false,
  "cookies": [],
  "body": "eyJtZXNzYWdlIjoi...dCBleGlzdC4ifV19fQ=="
}

Passing my desired response object directly into the InvocationResult Value does give me the expected response body and seems much simpler.

However neither method seems to enable me to set the response status code.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 17 (8 by maintainers)

Most upvoted comments

Took another look at the issue. You are not getting the desired behavior(404 status code for http response and exception message as the body of the response) because you are not using the correct return type for your http trigger function. You are using void as the return type for the ThrowException method. If you want to return a valid http response from your function, you should use HttpResponseData as the return type of your function.

The below code should work.

[Function("ThrowException")]
public HttpResponseData ThrowException(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "throw-exception")] HttpRequestData req)
    => throw new System.Exception("Test message");

My previous comment was based on testing with the incorrect function code(with void as return type) 🤦

Let us know if you still run into issues. We will consider adding an analyzer to prevent users from using incorrect return types, in the future.

This is broken for the composite function return value. I am trying to craft an authorization middleware that short circuits HTTP requests and invoking this

var response = httpRequestData.CreateResponse(HttpStatusCode.Forbidden);
context.GetInvocationResult().Value = response;

having function returning composite return for multiple bindings results in 200 always, e.g.

        return new ComplexResponse
        {
            HttpResponse = ...
            ServiceBusResponse = ...
        };

This is fixed now and will be available in the next preview version of worker package we will publish (hopefully next week). Once the package is out, I will share an example of how to handle this use case.