-1
我有一個相當大的應用程序,有數十個Ajax調用。我想在單個地方記錄出現在ajax調用中的任何錯誤。我在我的_Layout.cshmtl視圖上放置了一個jquery警報,以便可以將異常傳遞給警報。如何從我的HandleExceptionAttribute類中返回錯誤字符串到我的視圖?在一個地方處理所有Ajax異常,並返回錯誤以查看
控制器動作:
[HandleExceptionAttribute]
[HttpPost]
[Authorize (Roles = "View Only,Admin,A-Team Manager,A-Team Analyst")]
public JsonResult GetEntitySorMapTable (Decimal entityId)
{
//Added this line to hit my HandleExceptionAttribute
throw new DivideByZeroException();
List<EntitySorMapView> entitySorMaps = null;
if (entityId == 0)
{
entitySorMaps = new List<EntitySorMapView> ();
}
entitySorMaps = RealmsModel.RealmsDataInterface ().SelectEntitySorMapByEntityId (entityId);
String data = HtmlHelpers.BuildEntitySorMapTable (entitySorMaps);
return new JsonResult ()
{
Data = data,
MaxJsonLength = Int32.MaxValue
};
}
錯誤屬性:
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);
}
}
}
_layout查看Ajax錯誤的腳本:
<script type="text/javascript">
$(document).ajaxError(function (xhr, status, error) {
e.stopPropagation();
if (xhr.error != null)
alert('Error: ' + xhr.responseText + ' status: ' + status + ' Exception: ' + error);
});
</script>