对于我的ios应用程序,我需要处理那些服务器返回错误的情况,有几个我感兴趣的错误处理,如未找到和超时。
我正在开发Xamarin和Windows Azure移动服务。到目前为止,我知道如何捕获这些异常,但是,在发生异常的情况下,我想显示一个包含刷新按钮的视图,用户可以按下该按钮以进行刷新(转到服务器,查看是否有新数据,删除刷新视图,并显示新信息)。
这就是我如何捕获由服务器抛出的异常:
public async RefreshAsync(){
try
{
var results = await DailyWorkoutTable.ToListAsync();
wod = results.FirstOrDefault();
SetupUI();
}
catch(Exception e)
{
var ex = e.GetBaseException() as MobileServiceInvalidOperationException;
if(ex.Response.StatusCode == 404)
{
//this is where I need to set up the refresh view and
//and add a UIButton to it
Console.WriteLine("Daily workout not found");
}
}
}
我不知道什么是正确的方法来完成这个。如果我创建一个UIView并添加一个UIButton给它,再用一个调用RefreshAsync的事件,它不会工作,也不是最优雅的方法。
有其他方法吗??请帮助。
您可以使用以下示例作为起点:
/// <summary>
/// A class for performing Tasks and prompting the user to retry on failure
/// </summary>
public class RetryDialog
{
/// <summary>
/// Performs a task, then prompts the user to retry if it fails
/// </summary>
public void Perform(Func<Task> func)
{
func().ContinueWith(t =>
{
if (t.IsFaulted)
{
//TODO: you might want to log the error
ShowPopup().ContinueWith(task =>
{
if (task.IsCompleted)
Perform(func);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
/// <summary>
/// Wraps a retry/cancel popup in a Task
/// </summary>
private Task ShowPopup()
{
var taskCompletionSource = new TaskCompletionSource<bool>();
var alertView = new UIAlertView("", "Something went wrong, retry?", null, "Ok", "Cancel");
alertView.Dismissed += (sender, e) => {
if (e.ButtonIndex == 0)
taskCompletionSource.SetResult(true);
else
taskCompletionSource.SetCanceled();
};
alertView.Show();
return taskCompletionSource.Task;
}
}
使用它:
var retryDialog = new RetryDialog();
retryDialog.Perform(() => DoSomethingThatReturnsTask());
这个例子是在async/await支持之前,但是如果需要的话,你可以重构它。
你也可以考虑让Perform()返回一个Task并变成异步的——这取决于你的用例。