【发布时间】:2015-10-19 19:47:16
【问题描述】:
我有一个相当大的应用程序,其中包含几十个 Ajax 调用。我想在一个地方记录 ajax 调用中出现的任何错误。我在我的 _Layout.cshmtl 视图上放置了一个 jquery 警报,以便可以将异常传递到警报中。如何将错误字符串从 HandleExceptionAttribute 类返回到我的视图?
控制器动作:
[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 View 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>
【问题讨论】:
标签: ajax asp.net-mvc-4 asp.net-ajax