autorest icon indicating copy to clipboard operation
autorest copied to clipboard

Generated code does not handle a null response when there's no default in the responses section

Open tbombach opened this issue 10 years ago • 3 comments

If an operation doesn't define a default in the responses section, our fallback logic for handling unexpected status codes is to try to read the response content stream as a string: https://github.com/Azure/autorest/blob/master/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml#L296

            if ((int)_statusCode != 200 && (int)_statusCode != 204)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);

However, if the Content property is null, this will throw a null reference exception.

tbombach avatar Jun 14 '16 23:06 tbombach

@pscofield When you get a chance, could you add more info to this bug (e.g. Swagger)

Copy & pasted from an offline conversation:

The strange thing is that we have tests that go to server endpoints that return null (that's the expected behavior in this test case and the associated model code). They try to deserialize into a model, but they always run Content.ReadAsStringAsync() first (which should repro this issue), before checking for null. That's why it's weird to me that Content is null in this case, rather than just a stream with no content.

Also, I'm not seeing anything when searching online about HttpResponseMessage.Content being null. There seems to be something strange in this specific case with how HttpClient.Send() is working. I was looking through our test suite and there are lots of tests that run HttpResponseMessage.Content.ReadAsStringAsync() when the server response has no body.

tbombach avatar Jun 14 '16 23:06 tbombach

What's the ETA on this? It blocks my check-in for LogicApps SDK since the tests are broken. Thanks.

pscofield avatar Jun 21 '16 01:06 pscofield

@pscofield I sent out a PR that I believe fixes this issue. Could you check if the null check fixes the problem in your code? (see the comment that I tagged you in when I sent out the PR for instructions: https://github.com/Azure/autorest/pull/1170#discussion_r67376399)

tbombach avatar Jun 21 '16 16:06 tbombach