I created a custom exception handling method as shown below and I can catch the database constraint exception with it and return the error to error method of AJAX call. However, when trying to create an exception using throw new Exception()" or throw new ArgumentNullException("instance") I encounter an error as displayed on the image below. Is there any mistake in the custom method? Or how can I test properly test it if it works for AJAX request and Normal request? Any help would be appreciated...
public class CustomErrorHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//If the request is AJAX return JSON, else return View
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
// Log exception first
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
Data = new
{
success = false,
message = "Error occured",
type = filterContext.Exception.GetType().Name,
exception = filterContext.Exception.ToString(),
number = ((System.Data.SqlClient.SqlException)filterContext.Exception.InnerException.InnerException).Number
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
// Let the system know that the exception has been handled
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
else
{
// Normal Exception. So, let it handle by its default ways
base.OnException(filterContext);
}
}
}