Two parts to resolve this issue, create a new exception, let it throw a StatusException with your message and throw it when you catch the normal exception:
try { SecurityManager.AddUpdateUserAgent(ua); } catch (Exception ex) { throw new StatusException("Your error message here") } return PartialView("AddModifyUserPartialView");
Override controller :: OnException and handle the exception, setting it to handle, setting the error code to 500, setting HttpContext.Response.StatusDescription in the StatusException message. For instance:
protected override void OnException(ExceptionContext filterContext) { if (filterContext.Exception == null) return; Type exceptionType = filterContext.Exception.GetType(); if (exceptionType == typeof(StatusException)) { filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8; filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message; } }
Then, in the OnFailure handler for Ajax.BeginForm, display the error parameter:
function handleError(data){
By setting the error code to 500 in the OverException override, AjaxForm will detect the error and go to your handler. We also set the StatusDescription in the override so that the message is available in the handleError callback.
source share