10000 Throw exceptions for failure status codes with more data about the response in them. by bennor · Pull Request #45 · reactiveui/refit · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Throw exceptions for failure status codes with more data about the response in them. #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 6, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion Refit-Tests/RestService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net;
using System.Net.Http;
using NUnit.Framework;
using System.Threading.Tasks;
Expand Down Expand Up @@ -46,6 +47,9 @@ public interface IGitHubApi

[Get("/")]
Task<HttpResponseMessage> GetIndex();

[Get("/give-me-some-404-action")]
Task NothingToSeeHere();
}

public class RootObject
Expand Down Expand Up @@ -111,7 +115,7 @@ public void PostToRequestBin()
ae.Handle(
x =>
{
if (x is HttpRequestException)
if (x is ApiException)
{
// we should be good but maybe a 404 occurred
return true;
Expand All @@ -123,6 +127,22 @@ public void PostToRequestBin()
}
}

[Test]
public async Task CanGetDataOutOfErrorResponses()
{
var fixture = RestService.For<IGitHubApi>("https://api.github.com");
try {
await fixture.NothingToSeeHere();
Assert.Fail();
}
catch (ApiException exception) {
Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
var content = exception.GetContentAs<dynamic>();
Assert.AreEqual("Not Found", (string)content.message);
Assert.IsNotNull((string)content.documentation_url);
}
}

public interface IRequestBin
{
[Post("/1h3a5jm1")]
Expand Down
64 changes: 61 additions & 3 deletions Refit/RequestBuilderImplementation.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
using System;
using System.Net;
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Web;
using HttpUtility = System.Web.HttpUtility;
using System.Threading;

namespace Refit
Expand Down Expand Up @@ -180,7 +182,9 @@ Func<HttpClient, object[], Task> buildVoidTaskFuncForMethod(RestMethodInfo restM
var rq = factory(paramList);
var resp = await client.SendAsync(rq);

resp.EnsureSuccessStatusCode();
if (!resp.IsSuccessStatusCode) {
throw await ApiException.Create(resp);
}
};
}

Expand All @@ -195,7 +199,9 @@ Func<HttpClient, object[], Task<T>> buildTaskFuncForMethod<T>(RestMethodInfo res
return resp as T;
}

resp.EnsureSuccessStatusCode();
if (!resp.IsSuccessStatusCode) {
throw await ApiException.Create(resp);
}

var content = await resp.Content.ReadAsStringAsync();
if (restMethod.SerializedReturnType == typeof(string)) {
Expand Down Expand Up @@ -511,4 +517,56 @@ void determineReturnTypeInfo(MethodInfo methodInfo)
throw new ArgumentException("All REST Methods must return either Task<T> or IObservable<T>");
}
}

public class ApiException : Exception
{
public HttpStatusCode StatusCode { get; private set; }
public string ReasonPhrase { get; private set; }
public HttpResponseHeaders Headers { get; private set; }

public HttpContentHeaders ContentHeaders { get; private set; }
public string Content { get; private set; }
public bool HasContent
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⬆️

get { return !string.IsNullOrWhiteSpace(Content); }
}

private ApiException(HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never use the private keyword

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry about that. Thought I got them all, but old habits...

: base(createMessage(statusCode, reasonPhrase)) {
StatusCode = statusCode;
ReasonPhrase = reasonPhrase;
Headers = headers;
}

public T GetContentAs<T>()
{
return HasContent
? JsonConvert.DeserializeObject<T>(Content)
: default(T);
}

public static async Task<ApiException> Create(HttpResponseMessage response) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⬇️

var exception = new ApiException(response.StatusCode, response.ReasonPhrase, response.Headers);

if (response.Content == null) return exception;

try {
exception.ContentHeaders = response.Content.Headers;
exception.Content = await response.Content.ReadAsStringAsync();
response.Content.Dispose();
}
catch {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⬆️

// We're already handling an exception at this point,
// so we want to make sure we don't throw another one
// that hides the real error.
}

return exception;
}

static string createMessage(HttpStatusCode statusCode, string reasonPhrase)
{
return string.Format("Response status code does not indicate success: {0} ({1}).", (int)statusCode, reasonPhrase);
}
}
}
0