我在开发一个应用程序,客户端向服务器发送请求。服务器使用node.js编写,客户端使用flurl.Http编写的.NET。
当服务器上的请求失败时,创建自定义错误消息总是很有用的。例如:
request.respond(500, { message: "targetid is mandatory" });
然而,这会在客户端触发一个FlurlHttpException,并且响应中的JSON信息会丢失。
当从服务器接收到非成功响应代码时,我该如何接收此JSON信息呢?
我在开发一个应用程序,客户端向服务器发送请求。服务器使用node.js编写,客户端使用flurl.Http编写的.NET。
当服务器上的请求失败时,创建自定义错误消息总是很有用的。例如:
request.respond(500, { message: "targetid is mandatory" });
然而,这会在客户端触发一个FlurlHttpException,并且响应中的JSON信息会丢失。
当从服务器接收到非成功响应代码时,我该如何接收此JSON信息呢?
由于Flurl专注于以尽可能少的按键次数从URL到反序列化响应体,因此经常会被问及如何处理错误响应,其中响应体几乎总是与成功响应不同。这就是为什么Flurl默认在非2XX响应上抛出异常,以便您可以像这样处理错误响应:(参见链接)
try {
var t = await "http://api.com".GetJsonAsync<T>();
}
catch (FlurlHttpException ex) {
var error = await ex.GetResponseJsonAsync<TError>();
}
有几种变化:
ex.GetResponseStringAsync();
ex.GetResponseJsonAsync(); // returns a dynamic
OnError
,我能否使用它来包装 FlurlHttpException
为另一种类型并重新抛出它?顺便说一下,感谢您提供的这个很棒的框架。 - user1679671OnError
的一个相当常见的用例。https://flurl.io/docs/configuration/#event-handlers - Todd Menierpublic 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)); });
}
}
async void FakeLogin()
{
try{
User user = await LoginWithEmail ("fakeEmail@me.com", "fakePassword");
}
catch(MyApiException e) {
MyApiError = e.Error;
}
}
基本上
对于FlurlHttpException情况,我会在ReadAsStringAsync中进行延续,其中我声明延续返回一个User,但在延续内部,我总是抛出异常。
此外
您可以重构异常处理为以下简短形式:
catch (FlurlHttpException e) {
return await MyApiException.FromFlurlException<User>(e);
}