public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled) return;
        if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500) return;
        if (!ExceptionType.IsInstanceOfType(filterContext.Exception)) return;

        string controllerName = filterContext.GetController();
        string actionName = filterContext.GetAction();
        HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

        filterContext.Result = new ViewResult
        {
            ViewName = View,
            MasterName = Master,
            ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
        };

        //使用log4net写入本地日志
        _logger.Error(filterContext.Exception.Message, filterContext.Exception);

        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        filterContext.ExceptionHandled = true;
    }
        public void OnException(ExceptionContext filterContext)
        {
            // Log should go here
            if (filterContext.HttpContext.IsCustomErrorEnabled && !filterContext.ExceptionHandled)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                HandleErrorInfo info = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 

                if (!filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var errorModel = new ErrorModel(filterContext.Exception.Message, filterContext.Exception, controllerName, actionName);
                    filterContext.Result = new ViewResult { ViewName = "Error" , ViewData = new ViewDataDictionary(errorModel), TempData = filterContext.Controller.TempData };
                }
                else
                {
                    // It should return an JSON response and application should be prepared to display it
                }

            }
        }
Example #3
1
 // GET: Error
 public ActionResult Index()
 {
     //If a 404 is thrown, the system redirects here but without a HandleErrorInfo object, so we make our own.
     HttpException err = new HttpException(404, string.Format("404 - Unrecognized Url - ({0})", Request.Params["aspxerrorpath"]));
     HandleErrorInfo model = new HandleErrorInfo(err, "Error", "Index");
     return View("Error", model);
 }
        public override void OnException(ExceptionContext filterContext)
        {

            if (filterContext == null) throw new ArgumentNullException("filterContext");
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) return;
            var exception = filterContext.Exception;
            if (new HttpException(null, exception).GetHttpCode() != 500) return;
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            ActionResult result;
            if (IsJson)
                result = new JsonResult { Data = new { error = filterContext.Exception.Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            else {
                var dict = new ViewDataDictionary<HandleErrorInfo>(model);
                if (filterContext.Controller.ViewData.ContainsKey("KatushaUser")) dict.Add("KatushaUser", filterContext.Controller.ViewData["KatushaUser"]);
                if (filterContext.Controller.ViewData.ContainsKey("KatushaProfile")) dict.Add("KatushaProfile", filterContext.Controller.ViewData["KatushaProfile"]);
                dict.Add("HasLayout", HasLayout);
                result = new ViewResult { ViewName = ExceptionView, ViewData = dict, TempData = filterContext.Controller.TempData };
            }
            filterContext.Result = result;
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        public ActionResult AddActivity(CRM_KA_ActivityModel ActivityModel, string CustomerID)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    ActivityModel.Id = System.Guid.NewGuid();
                    ActivityModel.CustomerID = CustomerID;

                    _KeyAccountManager.saveActivity(ActivityModel);
                    updateKeyAccount(CustomerID);

                    ViewData["CustomerID"] = CustomerID;

                    return PartialView("_KA_ActivityList");
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                var modal = new HandleErrorInfo(ex, "KeyAccount", "Index");
                return View("Error", modal);
            }
        }
 public ActionResult BadRequest(string error)
 {
     var controllerName = (string)RouteData.Values["controller"];
     var actionName = (string)RouteData.Values["action"];
     var model = new HandleErrorInfo(new HttpException(500, error), controllerName, actionName);
     return View(model);
 }
Example #7
1
        //Handles Exceptions in the Code
        public override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            //var directory = Path.GetFullPath("Log/ExceptionLog.txt");
            //StreamWriter LogWriter = new StreamWriter(directory, true);
            //LogWriter.WriteLine("{0}, {1}, {2}, {3}, {4}", DateTime.Now, filterContext.Exception.Message, filterContext.Exception.InnerException, filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"]);
            //LogWriter.WriteLine("-----------------------------------------------------------------------------");
            //LogWriter.Close();

            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //if the request is an ajax request return the _Error view
                    filterContext.Result = new ViewResult()
                    {
                        ViewName = "_Error",
                        ViewData = new ViewDataDictionary(model)
                    };
                }
                else
                {
                    //if the request is not an ajax request return the Error view
                    filterContext.Result = new ViewResult()
                    {
                        ViewName = "Error",
                        ViewData = new ViewDataDictionary(model)
                    };
                }
            }
        }
Example #8
1
        public static void HandleException(this ExceptionContext filterContext)
        {
            var ex = filterContext.Exception;
            var contextResponse = filterContext.HttpContext.Response;

            LogException(ex);

            HttpException httpException = new HttpException(null, ex);
            int httpExceptionCode = httpException.GetHttpCode();

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(ex, controllerName ?? "Unknown", actionName ?? "Unknown");
            ViewResult result = new ViewResult
            {
                ViewName = "Error",
                MasterName = "_Layout",
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            
            filterContext.Result = result;
            filterContext.ExceptionHandled = true;
            contextResponse.Clear();
            contextResponse.StatusCode = httpExceptionCode;
            contextResponse.TrySkipIisCustomErrors = true;
        }
        public ActionResult Login(string userId, string password)
        {
            AccountInfo info = new AccountInfo();

            if (ModelState.IsValid)
            {
                info.userid = userId;
                info.password = password;
                try {
                    using (svcClient = new AccountServiceClient())
                    {
                        if (svcClient.Authenticate(info))
                        {
                            Session["IsAuthenticated"] = true;
                            Session["User"] = userId;
                            return View("LoggedIn");
                        }
                    }
                }
                catch (FaultException<AccountServiceFault> ex)
                {
                    HandleErrorInfo errorInfo = new HandleErrorInfo(ex, "Home", "Login");
                    return View("Error", errorInfo);
                }

            }
            ViewBag.LoginFailed = "Oops... user credential is not matched, please try again!";
            return View();
        }
        protected sealed override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string resultMessage = HandleUnauthorizedMessage();
            string resultResource = BuildAuthorizeResource(filterContext);

            // Log Access Denied
            if (Token != null) // Don't log anonymous
                AuthorizationLog.LogAccessDenied(Token.User.UserId, resultResource, resultMessage);

            // Build Response View
            var ex = new AccessDeniedException(resultMessage, resultResource);
            HandleErrorInfo model = new HandleErrorInfo(ex, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
            ViewResult result = new ViewResult
            {
                ViewName = "Error",
                MasterName = Token == null ? "_PublicLayout" : "_Layout",
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };

            filterContext.Result = result;
            var contextResponse = filterContext.HttpContext.Response;
            contextResponse.Clear();
            contextResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
            contextResponse.TrySkipIisCustomErrors = true;
        }
Example #11
1
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            if (this._logger.IsErrorEnabled)
            {
                this._logger.Error(string.Format("An unexpected error occured while executing {0} in {1}.", actionName, controllerName), exception);
            }

            MessageViewData messageViewData = new MessageViewData();

            while (exception != null)
            {
                messageViewData.AddErrorMessage(this._localizer.GetString(exception.Message));
                exception = exception.InnerException;
            }
            var viewData = new ViewDataDictionary<HandleErrorInfo>(model);
            viewData["Messages"] = messageViewData;

            // Render error view
            filterContext.Result = new ViewResult
                                   	{
                                   		ViewName = View,
                                   		MasterName = Master,
                                   		ViewData = viewData,
                                   		TempData = filterContext.Controller.TempData
                                   	};

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
        }
Example #12
0
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;
            if (new HttpException(null, exception).GetHttpCode() != 404)
            {
                return;
            }

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            filterContext.Result = new ViewResult
            {
                ViewName = this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        public ContentResult addAuthenticatedUser(string UserID)
        {
            try
            {
                if (ModelState.IsValid)
                {
                     HttpCookie CK = HttpContext.Request.Cookies.Get("LoginDetail");

                     if (CK != null)
                     {
                         SecurityUserModel entity = new SecurityUserModel();
                         entity.UserID = UserID;
                         entity.SubsystemID = Int32.Parse(CK.Values["SubSystemID"].ToString());

                         _SecurityManager.Save(entity);

                         return Content("success");
                     }
                     else
                     {
                         return Content("fail");
                     }
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                var modal = new HandleErrorInfo(ex, "SecuritySetting", "index");
                return Content("fail");
            }
        }
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ErrorResult
            {
                StatusCode = HttpStatusCode.InternalServerError,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
            };

            filterContext.ExceptionHandled = true;
        }
 public virtual void OnException(ExceptionContext filterContext)
 {
     if (filterContext == null)
     {
         throw new ArgumentNullException("filterContext");
     }
     if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
     {
         Exception innerException = filterContext.Exception;
         if ((new HttpException(null, innerException).GetHttpCode() == 404))
         {
             string controllerName = (string)filterContext.RouteData.Values["controller"];
             string actionName = (string)filterContext.RouteData.Values["action"];
             HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
             ViewResult result = new ViewResult
             {
                 ViewName = this.View,
                 MasterName = this.Master,
                 ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                 TempData = filterContext.Controller.TempData
             };
             filterContext.Result = result;
             filterContext.ExceptionHandled = true;
             filterContext.HttpContext.Response.Clear();
             filterContext.HttpContext.Response.StatusCode = 404;
             filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
             filterContext.HttpContext.Response.ClearHeaders();
         }
     }
 }
        public ActionResult CreateTechnicalSupport(TechnicalSupportModel entity)
        {
            if (_TechnicalSupportManager.getByID(entity.VisitedDate,entity.CustomerID,User.Identity.Name)!=null)
            {
                ModelState.AddModelError("*", "This Customer and Visited date are duplicated in record.");
                return View(new TechnicalSupportModel { CustomerID = entity.CustomerID }).WithErrorMessage("Duplicated record!");
            }
            try
            {
                // TODO: Add insert logic here
                entity.AttachGroupID = Guid.NewGuid();
                entity.CreatedBy = User.Identity.Name;
                entity.CreatedDate = DateTime.Today;

                _TechnicalSupportManager.Save(entity);

                List<FileAttachmentModel> FAList = (List<FileAttachmentModel>)Session["Attachment"];

                if (FAList != null)
                {
                    foreach (FileAttachmentModel item in FAList)
                    {
                        _FileAttachmentManager.Save(item,entity.AttachGroupID,User.Identity.Name);
                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                var modal = new HandleErrorInfo(ex, "TechnicalSupport", "CreateTechnicalSupport");
                return View("Error", modal);
            }
        }
Example #17
0
        private void ExceptionLog(int httpCode)
        {
            Log Log = new Log();

            Log.DateTime = DateTime.UtcNow;
            string controllerName = (string)RouteData.Values["controller"];
            string actionName     = (string)RouteData.Values["action"];
            string StringLogMessage;

            if (httpCode != 0)
            {
                HandleErrorInfo HandleErrorInfo = new System.Web.Mvc.HandleErrorInfo(new HttpException(httpCode, ""), controllerName, actionName);
                StringLogMessage = "Controler:" + HandleErrorInfo.ControllerName +
                                   "---Action:" + HandleErrorInfo.ActionName +
                                   "---Exception.Message" + HandleErrorInfo.Exception.Message;
            }
            else
            {
                StringLogMessage = "Controler:" + controllerName +
                                   "---Action:" + actionName +
                                   "---Exception.Message" + "Error.";
            }
            Log.Message = StringLogMessage;

            PseezEntContext db = new PseezEntContext();

            db.Logs.Add(Log);
            db.SaveChanges();
        }
        protected virtual ActionResult CreateActionResult(ExceptionContext filterContext, int statusCode)
        {
            var ctx = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
            var statusCodeName = ((HttpStatusCode)statusCode).ToString();
            var exceptionName = filterContext.Exception.GetType().Name.Replace("Exception", "");

            var viewName = string.Empty;
            viewName = SelectFirstView(ctx,
                                                "~/Views/Error/{0}.cshtml".FormatWith(exceptionName),
                                                "~/Views/Error/{0}.cshtml".FormatWith(statusCode),
                                                "~/Views/Error/{0}.cshtml".FormatWith(statusCodeName),
                                                "~/Views/Error/UnexpectedError.cshtml");

            var controllerName = "Error";
            var actionName = "Index";
            var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            var result = new ViewResult
                                {
                                    ViewName = viewName,
                                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
                                };
            result.ViewBag.StatusCode = statusCode;

            filterContext.RouteData.Values["view"] = viewName.Replace("~/Views/Error/", "").Replace(".cshtml", "");

            return result;
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="filterContext">当前请求</param>
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception exception = filterContext.Exception;
            string message;
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                if (exception is HttpAntiForgeryException)
                {
                   
                }
                //filterContext.Result = Json(new AjaxResult(message, AjaxResultType.Error));
                //filterContext.ExceptionHandled = true;
            }
            else
            {

                var error = new HandleErrorInfo(
                    exception,
                    filterContext.RouteData.Values["controller"].ToString(),
                    filterContext.RouteData.Values["action"].ToString());

                filterContext.Result = View("Error", error);
                filterContext.ExceptionHandled = true;
            }
        }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        result = 0,
                        message = filterContext.Exception.Message
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
 protected override void OnException(ExceptionContext filterContext)
 {
     var error = new HandleErrorInfo(
         filterContext.Exception,
         filterContext.RouteData.Values["controller"].ToString(),
         filterContext.RouteData.Values["controller"].ToString());
     View("Error", error).ExecuteResult(ControllerContext);
 }
        public override void OnException(ExceptionContext filterContext)
        {
            SystemMonitor.Error(filterContext.Exception, "Error executing request.");

            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }

            

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            // log the error using log4net.
            SystemMonitor.Error(filterContext.Exception, filterContext.Exception.Message);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        public override void OnException(ExceptionContext filterContext)
        {
            //if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            //{
            //    return;
            //}

            //if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            //{
            //    return;
            //}

            //if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            //{
            //    return;
            //}

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            log4net.ILog log = log4net.LogManager.GetLogger(filterContext.RouteData.Values["controller"].ToString());

            var msg = filterContext.Exception.Message;
            var ex = filterContext.Exception;

            log.Error(ex.ToString() + " | " + msg);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
Example #24
0
        public ActionResult Error(System.Web.Mvc.HandleErrorInfo errorInfo)
        {
            if (Request.IsAjaxRequest())
            {
                return(PartialView(errorInfo));
            }

            return(View(errorInfo));
        }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
               // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {

                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            // log the error by using your own method
            string message = string.Format("Controller Name : {0}, Action Method: {1}, Error Message :{2}", controllerName, actionName, filterContext.Exception.Message);
            ILogger logService = new LoggingService();
            logService.Error(message, filterContext.Exception);
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
            var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
            };
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            var model = new HandleErrorInfo(filterContext.Exception, "Error", "Index");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
            };
        }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)// || !filterContext.HttpContext.IsCustomErrorEnabled
            {
                return;
            }

            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName = View,
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            var exceptionHandled = filterContext.ExceptionHandled;
            ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        public override void OnException(ExceptionContext filterContext)
        {
            //filterContext.HttpContext.IsCustomErrorEnabled

            // only call when custom error is off
            // nếu trong mỗi action đã dùng try/cach để handle error, thì sẽ không làm gì
            if (filterContext.ExceptionHandled)
                return;

            //1. LogError
            Logger.DefaultLogger.Error(filterContext.Exception);

            #region 2. Redirect to the error page if exception wasn't handled yet.
            /*
         Note: If none of the exception filters for an action method set the ExceptionHandled property to true, 
            the MVC Framework uses the default ASP.NET exception handling procedure. 
            This will display the dreaded yellow screen of death by default.
                  
         * Lưu ý: Hiện tại trong mỗi controller đều khai báo atrribute [CustomHandleError]
            Nếu trong mỗi action chúng ta không dùng try-catch để handle error, thì mặc định sẽ vô hàm này
            Nếu set ExceptionHandled = false --> sẽ văng ra trang vàng lỗi
            Ngược lại ExceptionHandled = true -> sẽ nhảy vô trang error  "/Error/SpecialErrorPage"
         */

            if (HttpContext.Current.IsDebuggingEnabled)
            {
                filterContext.ExceptionHandled = false;
            }
            else
            {
                var model = new HandleErrorInfo(filterContext.Exception, filterContext.RouteData.Values["controller"].ToString(), filterContext.RouteData.Values["action"].ToString());
                var result = new ViewResult
                {
                    ViewName = "~/Views/Shared/Error.cshtml",
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                };

                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    // the controller action was invoked with an AJAX request
                    result.ViewName = "~/Views/Shared/ErrorAjax.cshtml";
                }
                filterContext.Result = result;

                filterContext.ExceptionHandled = true;
            }

            #endregion

            //2. maybe send mail to admin

        }
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            string          controllerName = (string)filterContext.RouteData.Values["controller"];
            string          actionName     = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model          = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ViewResult
            {
                ViewName   = View,
                MasterName = Master,
                ViewData   = new ViewDataDictionary <HandleErrorInfo>(model),
                TempData   = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            // Certain versions of IIS will sometimes use their own error page when
            // they detect a server error. Setting this property indicates that we
            // want it to try to render ASP.NET MVC's error page instead.
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
Example #31
0
 protected override void OnException(ExceptionContext filterContext)
 {
     Exception e = filterContext.Exception;
     string actionName = filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
     string controllerName = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
     HandleErrorInfo haErInfo = new HandleErrorInfo(e, controllerName, actionName);
     filterContext.ExceptionHandled = true;
     filterContext.Result = new ViewResult()
     {
         ViewName = "Error",
         ViewData = new ViewDataDictionary(haErInfo)
     };
 }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() == 404)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                filterContext.Result = new ViewResult
                {
                    ViewName = "404",
                    MasterName = Master,
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 404;

                // Certain versions of IIS will sometimes use their own error page when
                // they detect a server error. Setting this property indicates that we
                // want it to try to render ASP.NET MVC's error page instead.
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }

            if (!ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            base.OnException(filterContext);
        }
        //private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
            {
                return;
            }

            if (filterContext.Exception is HttpAntiForgeryException)
            {
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                string afgMessage = "Invalid post from URL" + filterContext.HttpContext.Request.Url.ToString();
                Logger.LogError("USAS - Antiforgery Error", afgMessage);
                return;
            }

            if (filterContext.Exception is HttpRequestValidationException)
            {
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                string xssMessage = "Invalid request sent: " + filterContext.Exception.Message;
                Logger.LogError("USAS - XSS Error", xssMessage);
                return;
            }

            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ViewResult
            {
                ViewName = View,
                MasterName = Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

            string errMsg = "Error in Controller: " + controllerName + " Action: " + actionName + " Error: " + model.Exception.Message;
            Logger.LogError("USAS - Unhandled Error", errMsg);
        }
Example #34
0
        public override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.Status = "500 Internal Server Error";
                filterContext.Result = new JsonResult {
                    Data = new { ErrorMessage = filterContext.Exception.Message }
                };
            }
            else
            {
                string actionName     = filterContext.RouteData.Values["action"].ToString();
                string controllerName = filterContext.RouteData.Values["controller"].ToString();
                var    model          = new System.Web.Mvc.HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                filterContext.Result = new ViewResult()
                {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary(model)
                };
            }
        }