我正在使用 HandleError属性处理 Controller 中的所有错误,该属性已针对 http和ajax 请求进行了修改,并将它们作为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();
}
}
}
并在每个 Controller 上将其用作:
[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>
我的问题是,当我只取消注释状态代码的remove标记时,它可以与httpErrors一起正常工作,但不能与ajax请求一起工作,因为它不返回状态代码,而是返回Home/Error页面。
但是,如果我评论此标签,则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请求错误:我想从操作返回页面。 (主页/错误)。
最佳答案
由于工作正常,我正在发布解决方案作为答案。
对于上述问题,而不是检查状态代码,请在Jquery AJAX中检查错误。
Sysntax同样是
error:Function( jqXHR jqXHR, String textStatus, String errorThrown ).
尝试将输出记录到控制台或警告以检查所需结果以进行处理。
如果要处理特定的响应,则抛出特定的错误,而不是一般错误。
关于ajax - 使用HandleError属性类处理Http和Ajax请求的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823172/