【发布时间】: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