Credo sia interessante gestire tutti gli errori http come eccezioni. Non sono sicuro se sia la migliore pratica, ma ho fatto un tentativo.
Quello che ho fatto è qualcosa di simile:
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)); });
}
}
Questo consente di gestire i casi di successo e di errore come questo:
async void FakeLogin()
{
try{
User user = await LoginWithEmail ("[email protected]", "fakePassword");
}
catch(MyApiException e) {
MyApiError = e.Error;
}
}
Fondamentalmente
Per il caso FlurlHttpException , Faccio una continuazione per ReadAsStringAsync dove dichiaro la continuazione per restituire un utente, ma nella continuazione io sempre lanciare un'eccezione
Inoltre
Si potrebbe refactoring l'eccezione manipolazioni devono essere il più breve:
catch (FlurlHttpException e) {
return await MyApiException.FromFlurlException<User>(e);
}
fonte
2015-01-21 18:16:57
Penso che la mia [nuova risposta] (http://stackoverflow.com/a/28332184/62600) dovrebbe essere quello che stai cercando. –