2

I have a issue regarding exception throwing and catching on client side. This has all worked well until I introduced HTTP401. This is my base controler than overrides OnExcpetion:

protected override void OnException(ExceptionContext filterContext)
{
    var exception = HandleException.Handle(filterContext.Exception); 
    filterContext.Exception = exception;

    if(exception is AuthenticationException)
        filterContext.HttpContext.Response.StatusCode = 401;
    else
        filterContext.HttpContext.Response.StatusCode = 500;

    filterContext.ExceptionHandled = true;
    filterContext.Result = new JsonResult()
    {
        Data = new { Message = filterContext.Exception.Message },
        ContentType = "json"             
    };
}

This is my AJAX call along with succes and error.

$.ajax(
{
    type: 'POST',
    url: loginRoute,
    data: formData,
    dataType: 'json',
    processData: false,
    contentType: false,
    statusCode: {
        401: function () {
           $('#authenticationErrorMessage').text(xhr.responseJSON.Message);
           $('#authenticationError').show();
       }
    },
    success: function (responseData) {
        $('#authenticationSucessMessage').text(responseData.Message);
        $('#authenticationSuccess').show();
        window.location.replace(responseData.Redirect);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        $('#authenticationErrorMessage').text(xhr.responseJSON.Message);
        $('#authenticationError').show();
    }
});

The problems is that neither status code nor error are called upon completion. Only success is called. If I set my StatusCode to 500 all works fine.

Robert
  • 2,407
  • 1
  • 24
  • 35

1 Answers1

0

You can globally handle it. May be below code help you.

$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
    if ( jqxhr.status== 401 ) {
      alert( "Triggered ajaxError handler." );
    }
});
Power Star
  • 1,724
  • 2
  • 13
  • 25
  • It does not work. I was curious so I set StatusCode to 403 in OnException method and sure enough the error was caught on client side. I have tested this with Chrome and Edge(just to see if there wasn't something with Chrome). – Robert Oct 14 '16 at 17:49