【问题标题】:Handle all Ajax exceptions in one place and return error to view在一处处理所有 Ajax 异常并返回错误以查看
【发布时间】: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


    【解决方案1】:

    你可以使用

    filterContext.Result = new JsonResult
    {
        Data = new { errorMessage = "Your custom error message" },
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
    

    在你的 _layout.cshtml 文件中

    $(document).ajaxError(function (event, jqxhr, settings, thrownError) {
        if (jqxhr.error != null) {
            var result = JSON.parse(jqxhr.responseText);
                console.log(result.errorMessage)
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      相关资源
      最近更新 更多