1

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).

Shahzad
  • 1,315
  • 2
  • 22
  • 42
  • Please go through http://stackoverflow.com/questions/2480006/what-is-the-difference-between-customerrors-and-httperrors – Amit Jan 24 '17 at 09:06
  • I am not just handling http errors but i also need to get status code in ajax request to properly handle errors. – Shahzad Jan 24 '17 at 09:15
  • But as per your code if Ajax request is there then you are always returning Status as 500. Aren't you? – Amit Jan 24 '17 at 09:17
  • yes, but it's only work when i remove those tags from httperrors. – Shahzad Jan 24 '17 at 09:21
  • Where you are handling status code in Jquery? As response? what about Ajax error:? – Amit Jan 24 '17 at 09:36
  • error is all in small letters. Also can you check by console log or alert if it is falling into error ? syntax for error is error: Function( jqXHR jqXHR, String textStatus, String errorThrown ). Can you try with this without removing remove tags? – Amit Jan 24 '17 at 09:57
  • thanks, its working but in response its HandleError attribute giving the 500 Error page. what if i want to get specific response? – Shahzad Jan 24 '17 at 11:19

1 Answers1

0

As it is working I am posting solution as answer. For above issue instead of checking statuscode check error in Jquery AJAX. Sysntax for the same is

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

Try to log output to console or alert to check desired result to handle.

And if you want to handle specific response then throw specific error not generic one.

Amit
  • 882
  • 6
  • 13
  • Thanks mate, additionally i need to return json result from HandleError Attribute because by default this attribute find and return [**Error page**](https://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.118).aspx) and i need json result not the page. – Shahzad Jan 25 '17 at 08:09
  • 1
    That's what I was referring to. As you specified statuscode as 500 in HandleError it matches your config so Error page is returned. If you specify returncode as custom one. I hope you will be able to get JSON result. – Amit Jan 25 '17 at 08:55
  • could you please provide any sample? – Shahzad Jan 25 '17 at 11:00