Nếu máy chủ gửi một số mã trạng thái khác với 200, thì lệnh gọi lại lỗi sẽ được thực thi:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
và để đăng ký một trình xử lý lỗi chung, bạn có thể sử dụng $.ajaxSetup()
phương pháp:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Một cách khác là sử dụng JSON. Vì vậy, bạn có thể viết một bộ lọc hành động tùy chỉnh trên máy chủ để bắt ngoại lệ và chuyển chúng thành phản hồi JSON:
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
};
}
}
và sau đó trang trí hành động bộ điều khiển của bạn với thuộc tính này:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
và cuối cùng gọi nó:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});