Skip to content

Commit

Permalink
Let it throw (#1962)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed Nov 8, 2022
1 parent e968fa8 commit 052357b
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 24 deletions.
27 changes: 27 additions & 0 deletions src/RestSharp/Extensions/HttpResponseExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) .NET Foundation and Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

namespace RestSharp.Extensions;

public static class HttpResponseExtensions {
internal static Exception? MaybeException(this HttpResponseMessage httpResponse)
=> httpResponse.IsSuccessStatusCode
? null
#if NETSTANDARD
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
#else
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode);
#endif
}
11 changes: 1 addition & 10 deletions src/RestSharp/Response/RestResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ CancellationToken cancellationToken
ContentLength = httpResponse.Content.Headers.ContentLength,
ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
ResponseStatus = calculateResponseStatus(httpResponse),
ErrorException = MaybeException(),
ErrorException = httpResponse.MaybeException(),
ResponseUri = httpResponse.RequestMessage!.RequestUri,
Server = httpResponse.Headers.Server.ToString(),
StatusCode = httpResponse.StatusCode,
Expand All @@ -102,15 +102,6 @@ CancellationToken cancellationToken
RootElement = request.RootElement
};

Exception? MaybeException()
=> httpResponse.IsSuccessStatusCode
? null
#if NETSTANDARD
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}");
#else
: new HttpRequestException($"Request failed with status code {httpResponse.StatusCode}", null, httpResponse.StatusCode);
#endif

Task<Stream?> ReadResponse() => httpResponse.ReadResponse(cancellationToken);

async Task<Stream?> ReadAndConvertResponse() {
Expand Down
24 changes: 12 additions & 12 deletions src/RestSharp/RestClient.Async.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ public partial class RestClient {

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

if (Authenticator != null)
await Authenticator.Authenticate(this, request).ConfigureAwait(false);
if (Authenticator != null) await Authenticator.Authenticate(this, request).ConfigureAwait(false);

var httpMethod = AsHttpMethod(request.Method);
var url = BuildUri(request);
Expand All @@ -61,7 +60,8 @@ public partial class RestClient {

using var timeoutCts = new CancellationTokenSource(request.Timeout > 0 ? request.Timeout : int.MaxValue);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken);
var ct = cts.Token;

var ct = cts.Token;

try {
var headers = new RequestHeaders()
Expand All @@ -70,13 +70,11 @@ public partial class RestClient {
.AddAcceptHeader(AcceptedContentTypes);
message.AddHeaders(headers);

if (request.OnBeforeRequest != null)
await request.OnBeforeRequest(message).ConfigureAwait(false);
if (request.OnBeforeRequest != null) await request.OnBeforeRequest(message).ConfigureAwait(false);

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

if (request.OnAfterRequest != null)
await request.OnAfterRequest(responseMessage).ConfigureAwait(false);
if (request.OnAfterRequest != null) await request.OnAfterRequest(responseMessage).ConfigureAwait(false);

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

if (response.Exception != null) {
return Options.ThrowOnAnyError ? throw response.Exception : null;
var exception = response.Exception ?? response.ResponseMessage?.MaybeException();

if (exception != null) {
return Options.ThrowOnAnyError ? throw exception : null;
}

if (response.ResponseMessage == null) return null;
Expand Down Expand Up @@ -141,7 +141,7 @@ static HttpMethod AsHttpMethod(Method method)
#if NETSTANDARD
Method.Patch => new HttpMethod("PATCH"),
#else
Method.Patch => HttpMethod.Patch,
Method.Patch => HttpMethod.Patch,
#endif
Method.Merge => new HttpMethod("MERGE"),
Method.Copy => new HttpMethod("COPY"),
Expand All @@ -157,11 +157,11 @@ public static class ResponseThrowExtension {

return response;
}

public static RestResponse<T> ThrowIfError<T>(this RestResponse<T> response) {
var exception = response.GetException();
if (exception != null) throw exception;

return response;
}
}
}
12 changes: 10 additions & 2 deletions test/RestSharp.Tests.Integrated/DownloadFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ namespace RestSharp.Tests.Integrated;
public sealed class DownloadFileTests : IDisposable {
public DownloadFileTests() {
_server = HttpServerFixture.StartServer("Assets/Koala.jpg", FileHandler);
_client = new RestClient(_server.Url);
var options = new RestClientOptions(_server.Url) { ThrowOnAnyError = true };
_client = new RestClient(options);
}

public void Dispose() => _server.Dispose();
Expand Down Expand Up @@ -46,6 +47,13 @@ public sealed class DownloadFileTests : IDisposable {
Assert.True(string.Compare("JFIF", tag, StringComparison.Ordinal) == 0);
}

[Fact]
public async Task Handles_File_Download_Failure() {
var request = new RestRequest("Assets/Koala1.jpg");
var task = () => _client.DownloadDataAsync(request);
await task.Should().ThrowAsync<HttpRequestException>().WithMessage("Request failed with status code NotFound");
}

[Fact]
public async Task Handles_Binary_File_Download() {
var request = new RestRequest("Assets/Koala.jpg");
Expand Down Expand Up @@ -76,4 +84,4 @@ public sealed class DownloadFileTests : IDisposable {

Assert.Equal(expected, fromTemp);
}
}
}

0 comments on commit 052357b

Please sign in to comment.