Skip to content

Commit c7eebdf

Browse files
committed
Fix for #1692 (#1511) and use charset for #1693
1 parent b2031e0 commit c7eebdf

File tree

5 files changed

+81
-31
lines changed

5 files changed

+81
-31
lines changed

src/RestSharp/Response/ResponseHandling.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace RestSharp;
1919

2020
static class ResponseHandling {
2121
public static string GetResponseString(this HttpResponseMessage response, byte[] bytes) {
22-
var encodingString = response.Content.Headers.ContentEncoding.FirstOrDefault();
22+
var encodingString = response.Content.Headers.ContentType?.CharSet;
2323
var encoding = encodingString != null ? TryGetEncoding(encodingString) : Encoding.Default;
2424
return encoding.GetString(bytes);
2525

@@ -37,7 +37,7 @@ Encoding TryGetEncoding(string es) {
3737
#if NETSTANDARD
3838
return response.Content.ReadAsStreamAsync();
3939
# else
40-
return response.Content.ReadAsStreamAsync(cancellationToken);
40+
return response.Content.ReadAsStreamAsync(cancellationToken)!;
4141
#endif
4242
}
4343
}

src/RestSharp/Response/RestResponse.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ CancellationToken cancellationToken
6969
async Task<RestResponse> GetDefaultResponse() {
7070
var readTask = request.ResponseWriter == null ? ReadResponse() : ReadAndConvertResponse();
7171
using var stream = await readTask.ConfigureAwait(false);
72-
var bytes = stream == null ? null : await stream.ReadAsBytes(cancellationToken).ConfigureAwait(false);
73-
var content = bytes == null ? null : httpResponse.GetResponseString(bytes);
72+
73+
var bytes = stream == null ? null : await stream.ReadAsBytes(cancellationToken).ConfigureAwait(false);
74+
var content = bytes == null ? null : httpResponse.GetResponseString(bytes);
7475

7576
return new RestResponse {
7677
Content = content,
@@ -80,6 +81,7 @@ async Task<RestResponse> GetDefaultResponse() {
8081
ContentLength = httpResponse.Content.Headers.ContentLength,
8182
ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
8283
ResponseStatus = httpResponse.IsSuccessStatusCode ? ResponseStatus.Completed : ResponseStatus.Error,
84+
ErrorException = MaybeException(),
8385
ResponseUri = httpResponse.RequestMessage!.RequestUri,
8486
Server = httpResponse.Headers.Server.ToString(),
8587
StatusCode = httpResponse.StatusCode,
@@ -91,6 +93,11 @@ async Task<RestResponse> GetDefaultResponse() {
9193
Cookies = cookieCollection
9294
};
9395

96+
Exception? MaybeException()
97+
=> httpResponse.IsSuccessStatusCode
98+
? null
99+
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
100+
94101
Task<Stream?> ReadResponse() => httpResponse.ReadResponse(cancellationToken);
95102

96103
async Task<Stream?> ReadAndConvertResponse() {

src/RestSharp/RestClient.Async.cs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,13 @@ public async Task<RestResponse> ExecuteAsync(RestRequest request, CancellationTo
3535
cancellationToken
3636
)
3737
.ConfigureAwait(false)
38-
: ReturnErrorOrThrow(response, internalResponse.Exception, internalResponse.TimeoutToken);
38+
: AddError(response, internalResponse.Exception, internalResponse.TimeoutToken);
39+
3940

4041
response.Request = request;
4142
response.Request.IncreaseNumAttempts();
42-
return response;
43+
44+
return Options.ThrowOnAnyError ? ThrowIfError(response) : response;
4345
}
4446

4547
async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationToken cancellationToken) {
@@ -120,18 +122,15 @@ record InternalResponse(HttpResponseMessage? ResponseMessage, Uri Url, Exception
120122
return stream == null ? null : await stream.ReadAsBytes(cancellationToken).ConfigureAwait(false);
121123
}
122124

123-
RestResponse ReturnErrorOrThrow(RestResponse response, Exception exception, CancellationToken timeoutToken) {
124-
if (exception is OperationCanceledException) {
125-
response.ResponseStatus = timeoutToken.IsCancellationRequested ? ResponseStatus.TimedOut : ResponseStatus.Aborted;
126-
}
127-
else {
128-
response.ResponseStatus = ResponseStatus.Error;
129-
}
125+
static RestResponse AddError(RestResponse response, Exception exception, CancellationToken timeoutToken) {
126+
response.ResponseStatus = exception is OperationCanceledException
127+
? timeoutToken.IsCancellationRequested ? ResponseStatus.TimedOut : ResponseStatus.Aborted
128+
: ResponseStatus.Error;
130129

131130
response.ErrorMessage = exception.Message;
132131
response.ErrorException = exception;
133132

134-
return Options.ThrowOnAnyError ? ThrowIfError(response) : response;
133+
return response;
135134
}
136135

137136
static RestResponse ThrowIfError(RestResponse response) {
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System.Net;
2+
using RestSharp.IntegrationTests.Fixtures;
3+
4+
namespace RestSharp.IntegrationTests;
5+
6+
[Collection(nameof(TestServerCollection))]
7+
public class RequestFailureTests {
8+
readonly RestClient _client;
9+
readonly TestServerFixture _fixture;
10+
11+
public RequestFailureTests(TestServerFixture fixture) {
12+
_client = new RestClient(fixture.Server.Url);
13+
_fixture = fixture;
14+
}
15+
16+
[Fact]
17+
public async Task Handles_GET_Request_Errors() {
18+
var request = new RestRequest("status?code=404");
19+
var response = await _client.ExecuteAsync(request);
20+
21+
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
22+
}
23+
24+
[Fact]
25+
public async Task Handles_GET_Request_Errors_With_Response_Type() {
26+
var request = new RestRequest("status?code=404");
27+
var response = await _client.ExecuteAsync<Response>(request);
28+
29+
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
30+
response.Data.Should().Be(null);
31+
}
32+
33+
[Fact]
34+
public async Task Throws_on_unsuccessful_call() {
35+
var client = new RestClient(new RestClientOptions(_fixture.Server.Url) { ThrowOnAnyError = true });
36+
var request = new RestRequest("status?code=404");
37+
38+
var task = () => client.ExecuteAsync<Response>(request);
39+
await task.Should().ThrowExactlyAsync<HttpRequestException>();
40+
}
41+
42+
[Fact]
43+
public async Task GetAsync_throws_on_unsuccessful_call() {
44+
var request = new RestRequest("status?code=404");
45+
46+
var task = () => _client.GetAsync(request);
47+
await task.Should().ThrowExactlyAsync<HttpRequestException>();
48+
}
49+
50+
[Fact]
51+
public async Task GetAsync_generic_throws_on_unsuccessful_call() {
52+
var request = new RestRequest("status?code=404");
53+
54+
var task = () => _client.GetAsync<Response>(request);
55+
await task.Should().ThrowExactlyAsync<HttpRequestException>();
56+
}
57+
58+
class Response {
59+
public string Message { get; set; }
60+
}
61+
}

test/RestSharp.IntegrationTests/AsyncTests.cs renamed to test/RestSharp.IntegrationTests/RequestTests.cs

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,4 @@ public async Task Can_Timeout_GET_Async() {
6161

6262
Assert.Equal(ResponseStatus.TimedOut, response.ResponseStatus);
6363
}
64-
65-
[Fact]
66-
public async Task Handles_GET_Request_Errors_Async() {
67-
var request = new RestRequest("status?code=404");
68-
var response = await _client.ExecuteAsync(request);
69-
70-
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
71-
}
72-
73-
[Fact]
74-
public async Task Handles_GET_Request_Errors_Async_With_Response_Type() {
75-
var request = new RestRequest("status?code=404");
76-
var response = await _client.ExecuteAsync<Response>(request);
77-
78-
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
79-
Assert.Null(response.Data);
80-
}
8164
}

0 commit comments

Comments
 (0)