Azure / autorest

OpenAPI (f.k.a Swagger) Specification code generator. Supports C#, PowerShell, Go, Java, Node.js, TypeScript, Python
MIT License
4.54k stars 728 forks source link

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

Closed tbombach closed 8 years ago

tbombach commented 8 years ago

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 commented 8 years ago

@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.

pscofield commented 8 years ago

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

tbombach commented 8 years ago

@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)