c#-服务器关闭时忽略客户端的异常
我使用RestSharp在客户端(Xamarin android应用程序)和我的服务器之间传递数据。c#-服务器关闭时忽略客户端的异常,c#,android,xamarin.android,C#,Android,Xamarin.android,我使用RestSharp在客户端(Xamarin android应用程序)和我的服务器之间传递数据。 当出现错误(通常是因为服务器停机)时,执行请求的方法会抛出异常。 我希望异常一直返回到调用它的方法,这样我就可以向用户抛出一个错误 例如,我想登录,但假设服务器已关闭 A-执行请求的方法 public Task<T> ExecuteAsync<T>(RestRequest request) where T : new() { var client = new Re
当出现错误(通常是因为服务器停机)时,执行请求的方法会抛出异常。
我希望异常一直返回到调用它的方法,这样我就可以向用户抛出一个错误 例如,我想登录,但假设服务器已关闭 A-执行请求的方法
public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
var client = new RestClient
{
BaseUrl = new Uri(BaseUrl),
Authenticator = new HttpBasicAuthenticator(_accountName, _password)
};
var taskCompletionSource = new TaskCompletionSource<T>();
client.ExecuteAsync<T>(request, restResponse =>
{
if (restResponse.ErrorException != null)
{
throw (new Exception("Server returned an error"));
}
taskCompletionSource.SetResult(restResponse.Data);
});
return taskCompletionSource.Task;
}
public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
var request = new RestRequest
{
Method = Method.POST,
Resource = "Login"
};
request.AddJsonBody(
new
{
accessNumber = accessNumber,
password = password,
token = token
});
var isDone = await Api.ExecuteAsync<LoginObject>(request);
return isDone;
}
现在,当我运行代码时,错误被抛出一个错误,应用程序崩溃,我希望它从A转到B,从B转到C,然后我将向用户显示一个错误
Edit:我试图放置一个try/catch块,但它仍然在a中抛出异常。更改方法
a
在签名中使用async
,然后将最后一行更改为返回等待任务完成源。任务代码>在您的A方法中,请使用taskCompletionSource.SetException
如下:
if (restResponse.ErrorException != null)
{
//throw new Exception("Server returned an error");
taskCompletionSource.SetException(new Exception("Server returned an error"));
}
else
{
taskCompletionSource.SetResult(restResponse.Data);
}
在B方法中,替换此行:
var isDone = await Api.ExecuteAsync<LoginObject>(request);
var isDone=wait Api.ExecuteAsync(请求);
使用此方法,可以将异常重新抛出给C方法:
LoginObject isDone=null;
try
{
isDone = await Api.ExecuteAsync<LoginObject>(request);
}
catch (Exception e)
{
throw e;
}
LoginObject isDone=null;
尝试
{
isDone=等待Api.ExecuteAsync(请求);
}
捕获(例外e)
{
投掷e;
}
您是否尝试过?您的代码对我来说不够清晰,但是您应该在RestRequest块中处理您的异常。调用方应该处理异常,内部方法应该全部抛出异常并将异常处理委托给上层level@msoliman这就是我想要的。rest请求中没有要处理的内容,因为服务器已关闭。我想从A->B->C和C中的返回显示一条消息,表明服务器已关闭。我该怎么做?异常不能在线程之间传递。您可以使用delegate
来处理它。我做的有点不同,但此行taskCompletionSource.SetException(新异常(“服务器返回错误”);这就是解决办法。非常感谢。
LoginObject isDone=null;
try
{
isDone = await Api.ExecuteAsync<LoginObject>(request);
}
catch (Exception e)
{
throw e;
}