Skip to content

Commit 052357b

Browse files
Let it throw (#1962)
1 parent e968fa8 commit 052357b

File tree

4 files changed

+50
-24
lines changed

4 files changed

+50
-24
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Copyright (c) .NET Foundation and Contributors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
//
15+
16+
namespace RestSharp.Extensions;
17+
18+
public static class HttpResponseExtensions {
19+
internal static Exception? MaybeException(this HttpResponseMessage httpResponse)
20+
=> httpResponse.IsSuccessStatusCode
21+
? null
22+
#if NETSTANDARD
23+
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
24+
#else
25+
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode);
26+
#endif
27+
}

src/RestSharp/Response/RestResponse.cs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ async Task<RestResponse> GetDefaultResponse() {
8989
ContentLength = httpResponse.Content.Headers.ContentLength,
9090
ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
9191
ResponseStatus = calculateResponseStatus(httpResponse),
92-
ErrorException = MaybeException(),
92+
ErrorException = httpResponse.MaybeException(),
9393
ResponseUri = httpResponse.RequestMessage!.RequestUri,
9494
Server = httpResponse.Headers.Server.ToString(),
9595
StatusCode = httpResponse.StatusCode,
@@ -102,15 +102,6 @@ async Task<RestResponse> GetDefaultResponse() {
102102
RootElement = request.RootElement
103103
};
104104

105-
Exception? MaybeException()
106-
=> httpResponse.IsSuccessStatusCode
107-
? null
108-
#if NETSTANDARD
109-
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
110-
#else
111-
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode);
112-
#endif
113-
114105
Task<Stream?> ReadResponse() => httpResponse.ReadResponse(cancellationToken);
115106

116107
async Task<Stream?> ReadAndConvertResponse() {

src/RestSharp/RestClient.Async.cs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,7 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo
5050

5151
using var requestContent = new RequestContent(this, request);
5252

53-
if (Authenticator != null)
54-
await Authenticator.Authenticate(this, request).ConfigureAwait(false);
53+
if (Authenticator != null) await Authenticator.Authenticate(this, request).ConfigureAwait(false);
5554

5655
var httpMethod = AsHttpMethod(request.Method);
5756
var url = BuildUri(request);
@@ -61,7 +60,8 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo
6160

6261
using var timeoutCts = new CancellationTokenSource(request.Timeout > 0 ? request.Timeout : int.MaxValue);
6362
using var cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken);
64-
var ct = cts.Token;
63+
64+
var ct = cts.Token;
6565

6666
try {
6767
var headers = new RequestHeaders()
@@ -70,13 +70,11 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo
7070
.AddAcceptHeader(AcceptedContentTypes);
7171
message.AddHeaders(headers);
7272

73-
if (request.OnBeforeRequest != null)
74-
await request.OnBeforeRequest(message).ConfigureAwait(false);
73+
if (request.OnBeforeRequest != null) await request.OnBeforeRequest(message).ConfigureAwait(false);
7574

7675
var responseMessage = await HttpClient.SendAsync(message, request.CompletionOption, ct).ConfigureAwait(false);
7776

78-
if (request.OnAfterRequest != null)
79-
await request.OnAfterRequest(responseMessage).ConfigureAwait(false);
77+
if (request.OnAfterRequest != null) await request.OnAfterRequest(responseMessage).ConfigureAwait(false);
8078

8179
return new InternalResponse(responseMessage, url, null, timeoutCts.Token);
8280
}
@@ -99,8 +97,10 @@ record InternalResponse(HttpResponseMessage? ResponseMessage, Uri Url, Exception
9997
request.CompletionOption = HttpCompletionOption.ResponseHeadersRead;
10098
var response = await ExecuteInternal(request, cancellationToken).ConfigureAwait(false);
10199

102-
if (response.Exception != null) {
103-
return Options.ThrowOnAnyError ? throw response.Exception : null;
100+
var exception = response.Exception ?? response.ResponseMessage?.MaybeException();
101+
102+
if (exception != null) {
103+
return Options.ThrowOnAnyError ? throw exception : null;
104104
}
105105

106106
if (response.ResponseMessage == null) return null;
@@ -141,7 +141,7 @@ static HttpMethod AsHttpMethod(Method method)
141141
#if NETSTANDARD
142142
Method.Patch => new HttpMethod("PATCH"),
143143
#else
144-
Method.Patch => HttpMethod.Patch,
144+
Method.Patch => HttpMethod.Patch,
145145
#endif
146146
Method.Merge => new HttpMethod("MERGE"),
147147
Method.Copy => new HttpMethod("COPY"),
@@ -157,11 +157,11 @@ public static RestResponse ThrowIfError(this RestResponse response) {
157157

158158
return response;
159159
}
160-
160+
161161
public static RestResponse<T> ThrowIfError<T>(this RestResponse<T> response) {
162162
var exception = response.GetException();
163163
if (exception != null) throw exception;
164164

165165
return response;
166166
}
167-
}
167+
}

test/RestSharp.Tests.Integrated/DownloadFileTests.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ namespace RestSharp.Tests.Integrated;
77
public sealed class DownloadFileTests : IDisposable {
88
public DownloadFileTests() {
99
_server = HttpServerFixture.StartServer("Assets/Koala.jpg", FileHandler);
10-
_client = new RestClient(_server.Url);
10+
var options = new RestClientOptions(_server.Url) { ThrowOnAnyError = true };
11+
_client = new RestClient(options);
1112
}
1213

1314
public void Dispose() => _server.Dispose();
@@ -46,6 +47,13 @@ public async Task AdvancedResponseWriter_without_ResponseWriter_reads_stream() {
4647
Assert.True(string.Compare("JFIF", tag, StringComparison.Ordinal) == 0);
4748
}
4849

50+
[Fact]
51+
public async Task Handles_File_Download_Failure() {
52+
var request = new RestRequest("Assets/Koala1.jpg");
53+
var task = () => _client.DownloadDataAsync(request);
54+
await task.Should().ThrowAsync<HttpRequestException>().WithMessage("Request failed with status code NotFound");
55+
}
56+
4957
[Fact]
5058
public async Task Handles_Binary_File_Download() {
5159
var request = new RestRequest("Assets/Koala.jpg");
@@ -76,4 +84,4 @@ public async Task Writes_Response_To_Stream() {
7684

7785
Assert.Equal(expected, fromTemp);
7886
}
79-
}
87+
}

0 commit comments

Comments
 (0)