我在 xamarin 工作并尝试使用一种方法使用所有服务。为此,我编写了一个 TaskExtension。这样我就可以从应用程序的每个页面调用该扩展方法。这是为了禁用按钮,显示加载屏幕,响应处理并从一个角度满足异常处理。我在下面附上我的代码。需要您对此解决方案的专家意见
这是我的扩展类
public static class TaskExtensions
{
public static async Task<ResultViewModel<U>> ExecuteAsyncOperation<U>(this Task<HttpResponseMessage> operation, object sender = null)
{
ResultViewModel<U> resultModel = new ResultViewModel<U>();
Button button = BeforeAsyncCall(sender);
try
{
await BackgroundOperation(operation, resultModel);
}
catch (Exception ex)
{
resultModel.Status = HttpStatusCode.InternalServerError;
resultModel.Errors = new List<string>() { "Some error occurred. Please try again." };
}
finally
{
AfterAsyncCall(button);
}
return resultModel;
}
static async Task BackgroundOperation<U>(Task<HttpResponseMessage> operation, ResultViewModel<U> resultModel)
{
HttpResponseMessage RawResult = await operation;
var Response = await RawResult.Content.ReadAsStringAsync();
resultModel.Status = RawResult.StatusCode;
if (RawResult.IsSuccessStatusCode)
{
var responseObj = await Task.Run(() => JsonConvert.DeserializeObject<U>(Response));
resultModel.Result = responseObj;
}
else
{
var responseErrorObj = await Task.Run(() => JsonConvert.DeserializeObject<ErrorModel>(Response));
resultModel.Errors = new List<string>();
foreach (var modelState in responseErrorObj.ModelState)
{
foreach (var error in modelState.Value)
{
resultModel.Errors.Add(error.ToString());
}
}
}
}
相关分类