如何使用IMobileServiceSyncTable-InsertAsync从后端服务器捕获异常?

时间:2018-07-02 19:23:11

标签: azure xamarin asp.net-web-api xamarin.forms azure-mobile-services

我正在使用Azure Mobile App中的IMobileServiceSyncTable。在后端服务器端的InsertAsync操作中,我对数据进行了一些验证,如果验证失败,我想从服务器端抛出Exception。我尝试返回InternalServerError(),抛出HttpResponseException,但从未在客户端运行过。我在服务器端调试了Post方法,服务器抛出异常或返回InternalServerError,但在移动客户端中,不会发生错误。

有人可以帮助我吗?

这是我在客户端的代码:

public async Task<bool> AddPaciente(Paciente novoPaciente)
{
    //other things

    try
    {
        await _pacienteTable.InsertAsync(novoPaciente);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
        Debug.WriteLine(e.StackTrace);

        throw new WebException(AppResources.MensagemFalhaConexaoServidorAzure);
    }

    await SyncPaciente();

    return true;
} 

这是我在后端服务器端的发布方法

// POST tables/Paciente
public async Task<IHttpActionResult> PostPaciente(Paciente novoPaciente)
{   

    //other things

    if (paciente != null)
    {
        var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("Já existe um paciente com esse token cadastrado.")
        };

        //throw new HttpResponseException(responseMessage);
        return InternalServerError(new Exception("Já existe um paciente com esse token cadastrado."));
    }
}

2 个答案:

答案 0 :(得分:0)

您应该收听响应状态代码。

login (build 1870)
3860 bytes of account info loaded
deposit currency is USD
1482 bytes of tester parameters loaded
7868 bytes of input parameters loaded
4257 bytes of symbols list loaded
expert file added: Experts\modularexpert.ex5. 23022 bytes loaded
file Files\Data\modular.csv read error
requested data synchronization error

答案 1 :(得分:0)

  

我正在使用Azure移动应用程序中的 IMobileServiceSyncTable 。在后端服务器端的InsertAsync操作中,我对数据进行了一些验证,如果验证失败,我想从服务器端抛出Exception。

对于IMobileServiceSyncTable,您正在处理An Offline Client,这意味着IMobileServiceSyncTable<T>.InsertAsync会将数据直接插入到移动客户端的本地SQLite存储中。在您手动调用MobileServiceClient.SyncContext.PushAsync()之前,本地数据存储将被推送到您的移动后端。对于这种方法,我建议您确保在将输入保存到本地数据存储之前需要先进行验证,否则,推送操作将失败,那么即使在输入之后,也需要强制客户端用户调整现有输入已成功添加。

如果您按如下方式使用An Online Client,则抛出异常的两种方法都将立即返回给客户。

var mobileClient= new MobileServiceClient("https://{your-mobile-app-name}.azurewebsites.net");
var _pacienteTable= mobileClient.GetTable<Paciente>();
await _pacienteTable.InsertAsync(novoPaciente);

此外,我使用以下代码行捕获异常:

try
{
    await table.InsertAsync(item);
}
catch (MobileServiceInvalidOperationException ex)
{
    //TODO:
    //await ex.Response.Content.ReadAsStringAsync(); //get detailed response content
}
catch (Exception e)
{
    //TODO: other uncaught exception
}

对于类似的问题,您可以利用Fiddler捕获网络跟踪以缩小此问题的范围,并确保客户端可以正确收到相关的响应。