Skip to content

Commit 178277c

Browse files
authored
fix: parsing error response for queries (influxdata#83)
1 parent 5433d79 commit 178277c

File tree

7 files changed

+73
-20
lines changed

7 files changed

+73
-20
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
### Bug Fixes
44
1. [#81](https://github.com/influxdata/influxdb-client-csharp/pull/81): Fixed potentially hangs on of WriteApi.Dispose()
55
1. [#82](https://github.com/influxdata/influxdb-client-csharp/pull/82): Avoid to deadlock when is client used in UI
6+
1. [#83](https://github.com/influxdata/influxdb-client-csharp/pull/83): Fixed parsing error response for 1.x
67

78
## 1.7.0 [2020-04-17]
89

Client.Core/Exceptions/InfluxException.cs

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.IO;
34
using System.Linq;
45
using System.Net;
56
using InfluxDB.Client.Core.Internal;
7+
using Newtonsoft.Json;
68
using Newtonsoft.Json.Linq;
79
using RestSharp;
810

@@ -53,40 +55,64 @@ public HttpException(string message, int status) : base(message, 0)
5355
/// </summary>
5456
public int? RetryAfter { get; set; }
5557

56-
public static HttpException Create(IRestResponse requestResult)
58+
public static HttpException Create(IRestResponse requestResult, object body)
5759
{
5860
Arguments.CheckNotNull(requestResult, nameof(requestResult));
5961

6062
var httpHeaders = LoggingHandler.ToHeaders(requestResult.Headers);
6163

62-
return Create(requestResult.Content, httpHeaders, requestResult.ErrorMessage, requestResult.StatusCode);
64+
return Create(body, httpHeaders, requestResult.ErrorMessage, requestResult.StatusCode);
6365
}
6466

65-
public static HttpException Create(IHttpResponse requestResult)
67+
public static HttpException Create(IHttpResponse requestResult, object body)
6668
{
6769
Arguments.CheckNotNull(requestResult, nameof(requestResult));
6870

69-
return Create(requestResult.Content, requestResult.Headers, requestResult.ErrorMessage, requestResult.StatusCode);
71+
return Create(body, requestResult.Headers, requestResult.ErrorMessage, requestResult.StatusCode);
7072
}
7173

72-
public static HttpException Create(string content, IList<HttpHeader> headers, string ErrorMessage, HttpStatusCode statusCode)
74+
public static HttpException Create(object content, IList<HttpHeader> headers, string ErrorMessage, HttpStatusCode statusCode)
7375
{
76+
string stringBody = null;
77+
var errorBody = new JObject();
7478
string errorMessage = null;
75-
JObject errorBody;
7679

7780
int? retryAfter = null;
7881
{
7982
var retryHeader = headers.FirstOrDefault(header => header.Name.Equals("Retry-After"));
8083
if (retryHeader != null) retryAfter = Convert.ToInt32(retryHeader.Value);
8184
}
8285

83-
if (string.IsNullOrEmpty(content))
84-
errorBody = new JObject();
85-
else
86-
errorBody = JObject.Parse(content);
87-
88-
if (errorBody.ContainsKey("message")) errorMessage = errorBody.GetValue("message").ToString();
86+
if (content != null)
87+
{
88+
if (content is Stream)
89+
{
90+
var stream = content as Stream;
91+
var sr = new StreamReader(stream);
92+
stringBody = sr.ReadToEnd();
93+
}
94+
else
95+
{
96+
stringBody = content.ToString();
97+
}
98+
}
8999

100+
if (!string.IsNullOrEmpty(stringBody))
101+
{
102+
try
103+
{
104+
errorBody = JObject.Parse(stringBody);
105+
if (errorBody.ContainsKey("message"))
106+
{
107+
errorMessage = errorBody.GetValue("message").ToString();
108+
}
109+
}
110+
catch (JsonException)
111+
{
112+
errorBody = new JObject();
113+
}
114+
}
115+
90116
var keys = new[] {"X-Platform-Error-Code", "X-Influx-Error", "X-InfluxDb-Error"};
91117

92118
if (string.IsNullOrEmpty(errorMessage))
@@ -95,6 +121,7 @@ public static HttpException Create(string content, IList<HttpHeader> headers, st
95121
.Select(header => header.Value.ToString()).FirstOrDefault();
96122

97123
if (string.IsNullOrEmpty(errorMessage)) errorMessage = ErrorMessage;
124+
if (string.IsNullOrEmpty(errorMessage)) errorMessage = stringBody;
98125

99126
return new HttpException(errorMessage, (int) statusCode)
100127
{ErrorBody = errorBody, RetryAfter = retryAfter};

Client.Core/Internal/AbstractQueryClient.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,11 @@ protected async Task Query(RestRequest query, Action<ICancellable, Stream> consu
8787
{
8888
responseStream = AfterIntercept((int)response.StatusCode, () => response.Headers, responseStream);
8989

90-
RaiseForInfluxError(response);
90+
RaiseForInfluxError(response, responseStream);
9191
consumer(cancellable, responseStream);
9292
};
9393

94-
await Task.Run(() => { RestClient.DownloadData(query, true); });
94+
await Task.Run(() => { RestClient.DownloadData(query, true); }).ConfigureAwait(true);
9595
if (!cancellable.IsCancelled())
9696
{
9797
onComplete();
@@ -195,7 +195,7 @@ private bool IsCloseException(Exception exception)
195195
return exception is EndOfStreamException;
196196
}
197197

198-
protected void RaiseForInfluxError(object result)
198+
protected void RaiseForInfluxError(object result, object body)
199199
{
200200
if (result is IRestResponse restResponse)
201201
{
@@ -206,7 +206,7 @@ protected void RaiseForInfluxError(object result)
206206
throw restResponse.ErrorException;
207207
}
208208

209-
throw HttpException.Create(restResponse);
209+
throw HttpException.Create(restResponse, body);
210210
}
211211

212212
var httpResponse = (IHttpResponse) result;
@@ -220,7 +220,7 @@ protected void RaiseForInfluxError(object result)
220220
throw httpResponse.ErrorException;
221221
}
222222

223-
throw HttpException.Create(httpResponse);
223+
throw HttpException.Create(httpResponse, body);
224224
}
225225

226226
protected class FluxResponseConsumerRecord : FluxCsvParser.IFluxResponseConsumer

Client.Legacy.Test/FluxClientQueryTest.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using NUnit.Framework;
1111
using WireMock.Matchers;
1212
using WireMock.RequestBuilders;
13+
using WireMock.ResponseBuilders;
1314

1415
namespace Client.Legacy.Test
1516
{
@@ -75,6 +76,30 @@ public async Task QueryError()
7576
}
7677
}
7778

79+
[Test]
80+
public async Task ErrorAsStream()
81+
{
82+
var response = Response.Create()
83+
.WithStatusCode(403)
84+
.WithBody("Flux query service disabled. Verify flux-enabled=true in the [http] section of the InfluxDB config.");
85+
86+
MockServer.Given(Request.Create().WithPath("/api/v2/query").UsingPost())
87+
.RespondWith(response);
88+
89+
try
90+
{
91+
await FluxClient.QueryAsync("from(bucket:\"telegraf\")");
92+
93+
Assert.Fail();
94+
}
95+
catch (InfluxException e)
96+
{
97+
Assert.AreEqual(e.Status, 403);
98+
Assert.AreEqual(e.Message,
99+
"Flux query service disabled. Verify flux-enabled=true in the [http] section of the InfluxDB config.");
100+
}
101+
}
102+
78103
[Test]
79104
public async Task QueryErrorSuccessResponse()
80105
{

Client.Legacy/FluxClient.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ private async Task<IRestResponse> ExecuteAsync(RestRequest request)
416416

417417
var response = await Task.Run(() => RestClient.Execute(request)).ConfigureAwait(false);
418418

419-
RaiseForInfluxError(response);
419+
RaiseForInfluxError(response, response.Content);
420420

421421
response.Content = AfterIntercept(
422422
(int) response.StatusCode,

Client/InfluxDBClient.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ protected internal InfluxDBClient(InfluxDBClientOptions options)
4242
_apiClient.RestClient.UserAgent = $"influxdb-client-csharp/{version}";
4343

4444
_exceptionFactory = (methodName, response) =>
45-
!response.IsSuccessful ? HttpException.Create(response) : null;
45+
!response.IsSuccessful ? HttpException.Create(response, response.Content) : null;
4646

4747
_setupService = new SetupService((Configuration) _apiClient.Configuration)
4848
{

Client/WriteApi.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ protected internal WriteApi(InfluxDBClientOptions options, WriteService service,
148148
// ReSharper disable once ConvertIfStatementToReturnStatement
149149
if (result.IsSuccessful) return Notification.CreateOnNext(result);
150150

151-
return Notification.CreateOnError<IRestResponse>(HttpException.Create(result));
151+
return Notification.CreateOnError<IRestResponse>(HttpException.Create(result, result.Content));
152152
})
153153
.Catch<Notification<IRestResponse>, Exception>(ex =>
154154
{

0 commit comments

Comments
 (0)