I find it interesting to treat all HTTP errors as exceptions. Not sure if this is the best practice, but I tried.
I did something like this:
public static async Task<User> LoginWithEmail (string email, string password){ try{ return await "http://myapi.com/login" .AppendPathSegment ("login") .SetQueryParams (new {email = email, password = password}) .WithHeader ("Accept", "application/json") .GetJsonAsync<User> (); }catch (FlurlHttpException e) { return await e.Call.Response.Content.ReadAsStringAsync () .ContinueWith<User> ((contentAsync) => { throw new MyApiException(JsonConvert.DeserializeObject<MyApiError> (contentAsync.Result)); }); } }
This allows you to handle success and error cases, for example:
async void FakeLogin() { try{ User user = await LoginWithEmail (" fakeEmail@me.com ", "fakePassword"); } catch(MyApiException e) { MyApiError = e.Error; } }
Basically
In the case of FlurlHttpException, I am making a continuation for ReadAsStringAsync, where I declare a continuation to return the user, but inside the continuation I always make an exception.
Additionally
You could reorganize exception handling as short:
catch (FlurlHttpException e) { return await MyApiException.FromFlurlException<User>(e); }
source share