关于jquery:ASP.NET MVC Ajax错误处理

ASP.NET MVC Ajax Error handling

当jqueryajax调用一个操作时,如何处理控制器中抛出的异常?

例如,我希望在Ajax调用期间,在任何类型的服务器异常上执行一个全局javascript代码,如果处于调试模式或只是一个正常的错误消息,则该代码将显示异常消息。

在客户端,我将调用Ajax错误的函数。

在服务器端,我需要编写一个自定义的actionfilter吗?


if the some different末地位比队列服务器200,the error is executed:回调P></

1
2
3
4
5
6
7
8
9
$.ajax({
    url: '/foo',
    success: function(result) {
        alert('yeap');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('oops, something bad happened');
    }
});

在全球注册和误差处理的方法:你可以用the $.ajaxSetup()P></

1
2
3
4
5
$.ajaxSetup({
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('oops, something bad happened');
    }
});

is to another方式使用JSON。我知道你可以写在custom action on the filter的数据库服务器transforms into them which渔获量和JSON响应:P></

1
2
3
4
5
6
7
8
9
10
11
12
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new JsonResult
        {
            Data = new { success = false, error = filterContext.Exception.ToString() },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

然后,装饰你的控制器action with this属性:P></

1
2
3
4
5
6
7
8
9
[MyErrorHandler]
public ActionResult Foo(string id)
{
    if (string.IsNullOrEmpty(id))
    {
        throw new Exception("oh no");
    }
    return Json(new { success = true });
}

最后invoke恩:布尔P></

1
2
3
4
5
6
7
$.getJSON('/home/foo', { id: null }, function (result) {
    if (!result.success) {
        alert(result.error);
    } else {
        // handle the success
    }
});


googling后写的简单数据库:基于MVC的行动handing filterP></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class HandleExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                    filterContext.Exception.StackTrace
                }
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}

在global.ascx和写入:P></

1
2
3
4
 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
      filters.Add(new HandleExceptionAttribute());
 }

然后我写这个脚本:on the页面布局或硕士学位P></

1
2
3
4
5
6
<script type="text/javascript">
      $(document).ajaxError(function (e, jqxhr, settings, exception) {
                       e.stopPropagation();
                       if (jqxhr != null)
                           alert(jqxhr.responseText);
                     });

最后,你应该把custom error)。然后享受它:)P></


不幸的是他/她are of answers,曼弗雷迪或法拉利吗我很好。surprisingly the solution is多简单的内部。返回从控制器:P></

1
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);

AS和EN标准误差的在线处理HTTP客户端作为你喜欢。P></


在协议与S反应在aleho' example是完整的。它的魅力和作品像是超级简单。P></

队列控制器P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[HttpGet]
public async Task<ActionResult> ChildItems()
{
    var client = TranslationDataHttpClient.GetClient();
    HttpResponseMessage response = await client.GetAsync("childItems);

    if (response.IsSuccessStatusCode)
        {
            string content = response.Content.ReadAsStringAsync().Result;
            List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
            return Json(content, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
        }
    }
}

在JavaScript代码视图P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var url = '@Html.Raw(@Url.Action("ChildItems","WorkflowItemModal")';

$.ajax({
    type:"GET",
    dataType:"json",
    url: url,
    contentType:"application/json; charset=utf-8",
    success: function (data) {
        // Do something with the returned data
    },
    error: function (xhr, status, error) {
        // Handle the error.
    }
});

希望这helps人*!P></


我在我的快速解决方案,因为它好和加工时间短。尽管我认为更好的选择是使用安the filter可以例外,也许我的解决方案,帮助在茶馆solution is needed无知。P></

我下面。在控制器的方法在jsonresult returned the property"的成功与"inside the日期:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    [HttpPut]
    public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
    {
        if (!ModelState.IsValid)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage ="Model is not valid", Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
        try
        {
            MyDbContext db = new MyDbContext();

            db.Entry(employeToSave).State = EntityState.Modified;
            db.SaveChanges();

            DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];

            if (employeToSave.Id == user.Id)
            {
                user.Company = employeToSave.Company;
                user.Language = employeToSave.Language;
                user.Money = employeToSave.Money;
                user.CostCenter = employeToSave.CostCenter;

                Session["EmployeLoggin"] = user;
            }
        }
        catch (Exception ex)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = ex.Message, Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }

        return new JsonResult() { Data = new { Success = true }, };
    }

以后我要呼叫在Ajax for this property知道如果我安的例外:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$.ajax({
    url: 'UpdateEmployeeConfig',
    type: 'PUT',
    data: JSON.stringify(EmployeConfig),
    contentType:"application/json;charset=utf-8",
    success: function (data) {
        if (data.Success) {
            //This is for the example. Please do something prettier for the user, :)
            alert('All was really ok');                                          
        }
        else {
            alert('Oups.. we had errors: ' + data.ErrorMessage);
        }
    },
    error: function (request, status, error) {
       alert('oh, errors here. The call to the server is not working.')
    }
});

本helps希望。快乐尾巴!:PP></


为处理从客户端Ajax on the errors在侧,在你assign erroroption to the function of the ajax呼叫。P></

在默认设置globally to the function,你可以使用这里描述的程序办理:api.jquery.com http:/ / / jquery.ajaxsetup。P></