Jeśli serwer wyśle kod stanu inny niż 200, zostanie wykonane wywołanie zwrotne błędu:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
i aby zarejestrować globalną obsługę błędów, możesz użyć $.ajaxSetup()
metody:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Innym sposobem jest użycie JSON. Możesz więc napisać niestandardowy filtr akcji na serwerze, który wyłapuje wyjątki i przekształca je w odpowiedź 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
};
}
}
a następnie udekoruj akcję kontrolera tym atrybutem:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
i na koniec przywołaj to:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});