หากเซิร์ฟเวอร์ส่งรหัสสถานะบางอย่างที่แตกต่างจาก 200 การเรียกกลับข้อผิดพลาดจะดำเนินการ:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
และในการลงทะเบียนตัวจัดการข้อผิดพลาดส่วนกลางคุณสามารถใช้$.ajaxSetup()
วิธีการ:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
อีกวิธีหนึ่งคือการใช้ JSON ดังนั้นคุณสามารถเขียนตัวกรองการดำเนินการที่กำหนดเองบนเซิร์ฟเวอร์ซึ่งจับข้อยกเว้นและแปลงเป็นการตอบสนอง 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
};
}
}
จากนั้นตกแต่งแอ็คชันคอนโทรลเลอร์ของคุณด้วยแอตทริบิวต์นี้:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
และในที่สุดก็เรียกมัน:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});