私はHttpResponseMessageメッセージからHttpErrorを引き出しようとしています。 Apiが例外をスローすると、HttpErrorとしてシリアル化されますが、404などのエラーはこの形式にはなりません。例外を使用せずにHttpResponseMessageからHttpErrorの結果を読み取る
私はHttpErrorを逆シリアル化しないとスローされた例外にキャッチして、このコードでこのバグを修正できました。
問題は現在、例外駆動型の開発を使用しています。
Idealy私はこのようなものが欲しいです。
var httpError = await response.Content.TryReadAsAsync<HttpError>(formatters);
if (httpError == null)
{
// Definetly not an HttpError and no exception thrown
}
確かに、HttpContentのコンテンツの種類を伝える簡単な方法でなければなりませんか?
public static async Task<ApiResponseMessage<T>> GetApiResponseAsync<T>(this HttpResponseMessage response, IEnumerable<MediaTypeFormatter> formatters) where T : class
{
if (!response.IsSuccessStatusCode)
{
HttpError httpError;
// Exception driven programming
try
{
// Could use string?
var contentString = response.Content.ReadAsStringAsync();
// This doesn't work. Throws exception if not correct type
var contentObject = await response.Content.ReadAsAsync<object>();
var alwaysNull = contentObject as HttpError;
httpError = await response.Content.ReadAsAsync<HttpError>(formatters);
}
catch (Exception)
{
httpError = null;
}
return new ApiResponseMessage<T>
{
IsSuccess = false,
HttpError = httpError,
Response = response
};
}
return new ApiResponseMessage<T>
{
IsSuccess = true,
Result = await response.Content.ReadAsAsync<T>(formatters),
Response = response
};
}