I am handling all the errors in controllers using the HandleError Attribute which i have modified for for http and ajax requests, and handling them as a 500 error type.
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();
}
}
}
and using it on each controller as:
[HandleExceptions]
public class InvoiceController : Controller
{}
I have also mode on the customErrors in web.config as:
<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>
and the httpErrors as:
<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>
The problem with me is that when I just uncomment the remove tag for status code then it's work fine with httpErrors but not with ajax request because instead of returning the status code it returns the Home/Error page. But if i comment this tag then httpErrors not return error page in most cases but work fine for ajax request which i can get in statusCode.
$.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");
}
}
});
What should I do to catch both side errors? Ajax request errors: I want to return the status code Http request errors: I want to return the page from an action. (Home/Error).