【问题标题】:Handle Errors for Http and Ajax requests using HandleError Attribute Class使用 HandleError 属性类处理 Http 和 Ajax 请求的错误
【发布时间】:2017-06-08 22:56:25
【问题描述】:

我正在使用为 http 和 ajax 请求修改的 HandleError 属性 处理控制器中的所有错误,并将它们作为 500 错误类型处理。

public class HandleExceptionsAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
            return;
        else
        {
            ErrorLogger.LogException(filterContext);

            if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
            {
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        success = false,
                        message = "error",
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                base.OnException(filterContext);
            }

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
        }
    }
}

并在每个控制器上使用它:

[HandleExceptions]
public class InvoiceController : Controller
{}

我也将 web.config 中的 customErrors 设置为:

<customErrors mode="On" >
  <error statusCode="400" redirect="Home/Error400" />
  <error statusCode="401" redirect="Home/Error401" />
  <error statusCode="403" redirect="Home/Error403" />
  <error statusCode="500" redirect="/Home/Error" />
</customErrors>

httpErrors 为:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <!--<remove statusCode="404" subStatusCode="-1" />-->
  <error statusCode="404" path="/Home/Error404" responseMode="ExecuteURL"/>
  <!--<remove statusCode="500" subStatusCode="-1" />-->
  <error statusCode="500" path="/Home/Error" responseMode="ExecuteURL"/>
</httpErrors>

我的问题是,当我只是取消注释状态代码的删除标记时,它适用于 httpErrors 但不适用于 ajax 请求,因为它不是返回状态代码,而是返回主页/错误页面。 但是,如果我评论这个标签,那么 httpErrors 在大多数情况下不会返回错误页面,但对于我可以在 statusCode 中获取的 ajax 请求工作正常。

$.ajax({
            url: "@Url.Action("SomeAction", "SomeController")",
            type: "POST",
            async: true,
            cache: false,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    catchSuccess("Success", response.responseText);
                }
                else {
                    catchWarning("Error", response.responseText);
                }
            },
            Error: function (ex) {
                catchError("Unkown Error", "Contact the Administrator");
            },
            statusCode: {
                500: function () {
                    catchError("Error 500", "Internal Server Error. Contact the Administrator");
                },
                403: function () {
                    catchError("Error 403", "Internal Server Error. Contact the Administrator");
                },
                404: function (response) {
                    catchError("Error 404", "Internal Server Error. Contact the Administrator");
                }
            }
        });

我应该怎么做才能捕捉到双方的错误? Ajax 请求错误:我要返回状态码 Http 请求错误:我想从操作中返回页面。 (主页/错误)。

【问题讨论】:

  • 我不仅在处理 http 错误,还需要在 ajax 请求中获取状态码以正确处理错误。
  • 但是根据您的代码,如果存在 Ajax 请求,那么您总是将状态返回为 500。不是吗?
  • 是的,但只有当我从 httperrors 中删除那些 标签时它才有效。
  • 您在哪里处理 Jquery 中的状态代码?作为回应? Ajax 错误呢?

标签: ajax asp.net-mvc error-handling http-error


【解决方案1】:

由于它正在工作,我正在发布解决方案作为答案。 对于上述问题,而不是检查 Jquery AJAX 中的状态码检查错误。 相同的语法是

error:Function( jqXHR jqXHR, String textStatus, String errorThrown ).

尝试将输出记录到控制台或警报以检查需要处理的结果。

如果您想处理特定响应,则抛出特定错误而不是通用错误。

【讨论】:

  • 谢谢伙计,另外我需要从 HandleError 属性返回 json 结果,因为默认情况下,此属性查找并返回 Error page,我需要 json 结果而不是页面。
  • 这就是我所指的。当您在 HandleError 中将状态码指定为 500 时,它与您的配置匹配,因此返回错误页面。如果您将返回代码指定为自定义代码。我希望你能得到 JSON 结果。
  • 能否提供样品?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多