在一个地方处理所有Ajax异常并返回错误以查看

时间:2015-10-19 19:47:16

标签: ajax asp.net-mvc-4 asp.net-ajax

我有一个相当大的应用程序,有几十个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查看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>

1 个答案:

答案 0 :(得分:0)

您可以使用

#!/usr/bin/env python

from uuid import UUID


def is_valid_uuid(uuid_to_test, version=4):
    """
    Check if uuid_to_test is a valid UUID.

    Parameters
    ----------
    uuid_to_test : str
    version : {1, 2, 3, 4}

    Returns
    -------
    `True` if uuid_to_test is a valid UUID, otherwise `False`.

    Examples
    --------
    >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a')
    True
    >>> is_valid_uuid('c9bf9e58')
    False
    """
    try:
        uuid_obj = UUID(uuid_to_test, version=version)
    except:
        return False

    return str(uuid_obj) == uuid_to_test


if __name__ == '__main__':
    import doctest
    doctest.testmod()

并在您的_layout.cshtml文件中

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