I'm trying to handle all ajax exceptions globally in my application.
I have a simple validation exception that is thrown after an ajax post request is sent to the server.
if (string.IsNullOrEmpty(name)) { throw new Exception("Name cannot be empty."); }
I have a class the overrides the OnException method:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = new JsonResult
{
Data = new { message = filterContext.Exception.Message },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
else
{
base.OnException(filterContext);
}
}
And a javascript function that listens to all ajax errors:
$(document).ajaxError(function(e, xhr, settings, exception) {
e.stopPropagation();
if (xhr.responseJSON != null) {
showMessage(xhr.responseJSON.message, ERROR);
}
});
The problem is, on my Azure server which is configured for https, the xhr.responseJSON is not returned. However, it works fine locally and I am able to display the exception message thrown. Is https somehow blocking the request? I have tried locally to run my application through https but I'm not able to recreate the issue.
I'm intending to use the same methodology for much more than just validation exceptions, as I know they can be easily handled from the client.