WebApi Catch连接超时错误

时间:2015-10-29 06:23:34

标签: javascript c# asp.net-mvc-4 asp.net-web-api error-handling

我有一个连接到WebApi 2.0的C#项目。

现在,该应用程序将用于使用3G数据连接的平板电脑。

我想捕获并输出一条友好的消息,通知他们应用程序无法联系服务器,请确保他们有3g的连接。

请问最好的方法是什么?

通常,加载视图的调用是使用javascript帖子进行的;

$.post('@Url.Action("Action", "Controller")',

我在失败事件中捕获;

.fail(function (xhr, textStatus, errorThrown) {
    // if connection issue then display an error message
})

我还必须“隐藏”webapi端点以停止url hacks等暴露它。因此调用实际上是对应用程序mvc控制器动作进行的,之后再调用api方法。

我在这里发现任何错误如下;

catch (HttpResponseException ex)
{
    var msg = ex.Response.Content.ReadAsStringAsync().Result;
    var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
    return new HttpStatusCodeResult(500, errorModel.errormessage);
}
catch (Exception ex)
{
    return new HttpStatusCodeResult(500, ex.Message);
}

AcknowledgeModel是一个异常过滤器,它将错误包装在指定的模型中。

1 个答案:

答案 0 :(得分:1)

超时是客户端错误。服务器永远不会告诉您连接超时 - 您将获得响应或请求实际上将超时。

因此,解决方案是使用客户端处理程序 对于jQuery AJAX,您可以使用.fail()来处理它 根据{{​​3}}:

  

第二个参数的可能值(除了null)是“timeout”,“error”,“notmodified”和“parsererror”。

所以,你可以这样轻松地做到这一点:

$.ajax({
    url: 'example.com',
    data: { }
}).done(function(r) {

}).fail(function(xhr, t, err) {
    if (t === "timeout") {
        alert("The connection has timed out. Please, check data connection availability");
    } else { 
        alert("Unknown server error. We are sorry!");
    }
});
相关问题