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 override void OnException(System.Web.Mvc.ExceptionContext filterContext) { filterContext.ExceptionHandled = true; if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { filterContext.RequestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var message = new ExceptionModel() { ExceptionMessage = filterContext.Exception.Message }; message.Message = "错误"; var jsonResult = new JsonResult() { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.Result = jsonResult; return; } ViewResult veiwResult = new ViewResult { ViewName = "Page_400", //错误页 MasterName = null, //指定母版页 ViewData = null, //指定模型 TempData = filterContext.Controller.TempData }; filterContext.Result = veiwResult; }
public void OnException(ExceptionContext filterContext) { Exception exception = filterContext.Exception; string message; if (filterContext.HttpContext.Request.IsAjaxRequest()) { message = "Ajax访问时引发异常:"; AjaxResult ajaxResult = null; if (exception is BusinessException) { message = exception.Message; ajaxResult = new AjaxResult(message, AjaxResultType.Warning); } else if (exception is HttpAntiForgeryException) { message += "安全性验证失败。<br>请刷新页面重试,详情请查看系统日志。"; } else { message += exception.Message; } filterContext.Result = new JsonResult() { Data = ajaxResult ?? new AjaxResult(message, AjaxResultType.Error) }; filterContext.ExceptionHandled = true; } else { filterContext.Result = new ContentResult() { Content = "系统异常:" + exception.Message }; } }
public void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled && filterContext.Exception!=null) { _logger.Error(filterContext.Exception.Message, filterContext.Exception); } }
public void OnException( ExceptionContext filterContext ) { _logger.Error(filterContext.Exception, filterContext.RouteData.Values["controller"] + "." + filterContext.RouteData.Values["action"] + filterContext.Exception.StackTrace.Split( '\n' ) [0] ); filterContext.ExceptionHandled = true; filterContext.Result = new ContentResult { Content = "Disaster occured" }; }
public override void OnException(ExceptionContext filterContext) { HttpStatusCode code = HttpStatusCode.InternalServerError; var ex = filterContext.Exception; string viewName = "Error500"; if (ex is ShortnrNotFoundException) { code = HttpStatusCode.NotFound; viewName = "Error404"; } if (ex is ShortnrConflictException) { code = HttpStatusCode.Conflict; viewName = "Error409"; } if (ex is ArgumentException) { code = HttpStatusCode.BadRequest; viewName = "Error400"; } filterContext.Result = new ViewResult() { ViewName = viewName }; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = (int)code; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }
protected override void OnException(ExceptionContext filterContext) { TempData["error500"] = filterContext.Exception.ToString(); filterContext.Result = new RedirectResult(Url.Action("Error500", "Home", new {area = "Admin"})); base.OnException(filterContext); }
//Helpers--------------------------------------------------------------------------------------------------------------// #region Helpers //getStatusCodeHelper private HttpStatusCode getStatusCodeHelper(ExceptionContext exceptionContext) { var exceptionType = exceptionContext.Exception.GetBaseException().GetType(); if (exceptionType == typeof(ArgumentNullException)) { return HttpStatusCode.BadRequest; } if (exceptionType == typeof(DbBadRequestException)) { return HttpStatusCode.BadRequest; } return HttpStatusCode.InternalServerError; }
public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled) return; var request = filterContext.HttpContext.Request; if (!request.IsAjaxRequest()) return; var exception = filterContext.Exception; var includeStackTrace = !filterContext.HttpContext.IsCustomErrorEnabled; var ajaxError = AjaxError.FromException(exception, includeStackTrace); if (ajaxError.ShouldLog) { Log.Error(exception, "An unhandled exception was thrown: {ErrorMessage}.", exception.Message); } filterContext.Result = new JsonNetResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ajaxError }; filterContext.HttpContext.Response.StatusCode = (int) ajaxError.StatusCode; filterContext.ExceptionHandled = true; }
public void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled) { var request = filterContext.RequestContext.HttpContext.Request; var message = string.Format("消息类型:{0}\r\n消息内容:{1}\r\n引发异常的方法:{2}\r\n引发异常源:{3}\r\n内部错误:{4}\r\n\r\n\r\n" , filterContext.Exception.GetType().Name , filterContext.Exception.Message , filterContext.Exception.TargetSite , filterContext.Exception.Source + filterContext.Exception.StackTrace, filterContext.Exception.InnerException ); if (request.IsAjaxRequest()) { //记录日志 LoggerHelper.Error(LoggerType.WebExceptionLog, message, filterContext.Exception); //转向 //filterContext.ExceptionHandled = true; //filterContext.Result = // new JsonResult { Data = new { Error = "网络错误,请刷新重试!", Info = message, Result = false, JsonRequestBehavior = true } }; } else { //记录日志 LoggerHelper.Error(LoggerType.WebExceptionLog, message, filterContext.Exception); //转向 //filterContext.ExceptionHandled = true; //filterContext.Result = new RedirectResult("/Admin/Home/Login"); } } }
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { filterContext.ExceptionHandled = true; string exceptionStr = string.Empty; try { if (filterContext.Exception != null) { exceptionStr = filterContext.Exception.StackTrace; throw filterContext.Exception; } } catch (HttpRequestValidationException) { if (filterContext.HttpContext.Request.UrlReferrer != null) { System.Web.HttpContext.Current.Response.Redirect(filterContext.HttpContext.Request.UrlReferrer.ToString()); } } catch (Exception ex) { ViewData["errMsg"] = ex.Message; ViewData["internalErrStackTrace"] = exceptionStr; filterContext.Result = new ViewResult { ViewName = "Error", ViewData = base.ViewData }; } _log.Fatal("[Error]", filterContext.Exception); _log.Fatal(string.Format("[ErrorStackTrace]:{0}", exceptionStr)); }
public void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled == true) { HttpException httpExp = filterContext.Exception as HttpException; if (httpExp.GetHttpCode() != 500) return; } HttpException httpException = filterContext.Exception as HttpException; if (httpException != null) { filterContext.Controller.ViewBag.UrlRefer = filterContext.HttpContext.Request.UrlReferrer; filterContext.HttpContext.Session["CurrentException"] = httpException; if (httpException.GetHttpCode() == 404) { filterContext.HttpContext.Response.Redirect("~/Login/NotFound"); } else if (httpException.GetHttpCode() == 500) { filterContext.HttpContext.Response.Redirect("~/Login/InternalError"); //filterContext.Result = new ViewResult() { ViewName = "InternalError", ViewData = filterContext.Controller.ViewData }; //filterContext.Result=new RedirectToRouteResult(("Default", new RouteValueDictionary(new { controller = "Login", action = "InternalError",route})); } //else if (httpException.GetHttpCode() == 900) //{ // filterContext.HttpContext.Response.Redirect("~/Login/SignIn"); //} } //record log in file filterContext.ExceptionHandled = true;//indicate the exp is handled }
protected override void OnException(ExceptionContext filterContext) { if (filterContext == null) return; //记录异常信息 ApplicationContext.ApplicationLog.Log(LoggerLevels.Error, filterContext.Exception); base.OnException(filterContext); }
public void OnException(ExceptionContext filterContext) { if (!(filterContext.Exception is HttpAntiForgeryException)) return; filterContext.Result = new RedirectResult("/"); filterContext.ExceptionHandled = true; }
protected override void OnException(ExceptionContext filterContext) { //Exception exception = filterContext.Exception; //string message; //if (filterContext.HttpContext.Request.IsAjaxRequest()) //{ // message = "Ajax访问时引发异常:"; // AjaxResult ajaxResult = null; // if (exception is BusinessException) // { // message = exception.Message; // ajaxResult = new AjaxResult(message, AjaxResultType.Warning); // } // else if (exception is HttpAntiForgeryException) // { // message += "安全性验证失败。<br>请刷新页面重试,详情请查看系统日志。"; // } // else // { // message += exception.Message; // } // filterContext.Result = Json(ajaxResult??new AjaxResult(message, AjaxResultType.Error)); // filterContext.ExceptionHandled = true; //} //else //{ // filterContext.Result =Content("系统异常:"+exception.Message); //} }
public override void OnException(ExceptionContext filterContext) { RedisHelper redis = new RedisHelper(1); redis.ListRightPush("errorMsg", "234234234"); filterContext.HttpContext.Response.Redirect("~/Error.html"); base.OnException(filterContext); }
public override void OnException(ExceptionContext context) { base.OnException(context); if (!context.ExceptionHandled) LogException(context.Exception); }
protected override void OnException(ExceptionContext filterContext) { try { StoreFrontConfiguration storeFrontConfig = GStoreDb.GetCurrentStoreFrontConfig(Request, true, false); if (storeFrontConfig == null) { AddUserMessage("Store Front Inactive or not found!", "Sorry, this URL does not point to an active store front. Please contact us for assistance.", AppHtmlHelpers.UserMessageType.Danger); filterContext.ExceptionHandled = true; RedirectToAction("Index", "Home", new { area = "" }).ExecuteResult(this.ControllerContext); } } catch (Exceptions.StoreFrontInactiveException) { AddUserMessage("Store Front Inactive!", "Sorry, this URL points to an Inactive Store Front. Please contact us for assistance.", AppHtmlHelpers.UserMessageType.Danger); filterContext.ExceptionHandled = true; RedirectToAction("Index", "Home", new { area = "" }).ExecuteResult(this.ControllerContext); } catch (Exceptions.NoMatchingBindingException) { AddUserMessage("Store Front Not Found!", "Sorry, this URL does not point to an active store front. Please contact us for assistance.", AppHtmlHelpers.UserMessageType.Danger); filterContext.ExceptionHandled = true; RedirectToAction("Index", "Home", new { area = "" }).ExecuteResult(this.ControllerContext); } catch (Exception) { throw; } base.OnException(filterContext); }
/// <summary> /// Called when an exception occurs. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.Exception != null) { //Call exception handler for logging the exception ExceptionManager.HandleException(filterContext.Exception); // Handling HTTP & Ajax requests. filterContext.ExceptionHandled = true; if (!filterContext.HttpContext.Request.IsAjaxRequest()) { // storing errormessage and stacktrace SessionStateManager<ErrorState>.Data.ErrorMessage = filterContext.Exception.Message; SessionStateManager<ErrorState>.Data.StackTrace = filterContext.Exception.StackTrace; // preparing redirect url Controller controller = (Controller)filterContext.Controller; string redirectUrl = controller.Url.SmartAction(ErrorControllerAction, ErrorController); filterContext.Result = new RedirectResult(redirectUrl); } else { filterContext.Result = OperationResult<bool>.CreateErrorResult( filterContext.Exception.Message, filterContext.Exception.StackTrace).ToJsonResult(); } } }
public void OnException(ExceptionContext filterContext) { if (filterContext.Exception != null) { string friendlyCaption = "An error has occured."; string friendlyMessage = filterContext.Exception.Message; string technicalDetails = filterContext.Exception.ToString(); filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { caption = friendlyCaption, message = friendlyMessage, details = technicalDetails } }; 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; } }
protected override void OnException(ExceptionContext filterContext) { //if (filterContext.ExceptionHandled) //{ // return; //} //if (this.Request.IsAjaxRequest()) //{ // var exception = filterContext.Exception as HttpException; // if (exception != null) // { // this.Response.StatusCode = exception.GetHttpCode(); // this.Response.StatusDescription = exception.Message; // } //} //else //{ // var controllerName = ControllerContext.RouteData.Values["controller"].ToString(); // var actionName = ControllerContext.RouteData.Values["action"].ToString(); // this.View(Views.Errors, new HandleErrorInfo(filterContext.Exception, controllerName, actionName)).ExecuteResult(this.ControllerContext); //} //filterContext.ExceptionHandled = true; }
protected override void OnException(ExceptionContext filterContext) { // 标记异常已处理 filterContext.ExceptionHandled = true; // 跳转到错误页 filterContext.Result = new RedirectResult(Url.Action("Error", "Shared")); }
public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled) { return; } if (ExceptionType.IsInstanceOfType(filterContext.Exception) == false) { return; } ActionResult result; if (filterContext.Exception.GetType() == typeof(ApplicationException)) { Console.ReadLine(); //result = GetCustomException(filterContext); //filterContext.HttpContext.Response.StatusCode = 400; //var id = GenerateNewGuid(); //LogException(filterContext.Exception, id); } else { } }
protected override void OnException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; string exceptionPolicy = this.ExceptionPolicyName; if (string.IsNullOrEmpty(exceptionPolicy)) { exceptionPolicy = DefautExceptionPolicyName; } try { if (ExceptionPolicy.HandleException(filterContext.Exception, exceptionPolicy)) { base.OnException(filterContext); } else { this.ModelState.AddModelError(Guid.NewGuid().ToString(), filterContext.Exception); filterContext.Result = this.View(); } } catch (Exception ex) { filterContext.Exception = ex; base.OnException(filterContext); } }
protected override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled) { return; } if (this.Request.IsAjaxRequest()) { var exception = filterContext.Exception as HttpException; if (exception != null) { this.Response.StatusCode = exception.GetHttpCode(); this.Response.StatusDescription = exception.Message; } } else { var controllerName = ControllerContext.RouteData.Values["Controller"].ToString(); var actionName = ControllerContext.RouteData.Values["Action"].ToString(); this.View("Error", new HandleErrorInfo(filterContext.Exception, controllerName, actionName)).ExecuteResult(this.ControllerContext); } filterContext.ExceptionHandled = true; }
public override void OnException(System.Web.Mvc.ExceptionContext 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; var httpException = exception as HttpException; if (httpException != null && httpException.GetHttpCode() != 500) { return; } //if (!ExceptionType.IsInstanceOfType(exception)) //{ // return; //} //filterContext.Controller.ViewData["ExceptionMessage"] = exception.Message; //BaseAppContext.Logger.Info(exception); //var section = System.Configuration.ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection; //filterContext.Result = new RedirectResult(section.DefaultRedirect); //filterContext.ExceptionHandled = true; base.OnException(filterContext); }
private void LogExceptionDetails(ExceptionContext exceptionContext) { var builder = new StringBuilder(); builder.Append("Unhandled exception from "); builder.AppendFormat(" {0}", exceptionContext.HttpContext.Request.UserHostAddress); string forwardedFor = exceptionContext.HttpContext.Request.Headers.Get("X-Forwarded-For"); if (!string.IsNullOrWhiteSpace(forwardedFor)) { builder.AppendFormat(" ({0})", forwardedFor); } builder.AppendFormat(" to: {0}", exceptionContext.HttpContext.Request.RawUrl); builder.AppendFormat( " - {0}/{1} {2}", exceptionContext.Controller.ControllerContext.RouteData.Values["controller"], exceptionContext.Controller.ControllerContext.RouteData.Values["action"], exceptionContext.HttpContext.Request.HttpMethod); builder.Append(Environment.NewLine); builder.Append("-------------"); builder.Append(Environment.NewLine); builder.Append(exceptionContext.Exception); _log.Error(builder.ToString(), exceptionContext.Exception); }
public void OnException(ExceptionContext filterContext) { if (filterContext.Controller is ServiceController) { ServiceController controller = (ServiceController)filterContext.Controller; object model; int httpStatusCode = (int)HttpStatusCode.InternalServerError; IServiceException serviceException = filterContext.Exception as IServiceException; if (serviceException!=null) { model = serviceException.Model; httpStatusCode = (int)serviceException.StatusCode; } else { model = ExceptionToErrorModel(filterContext.Exception); } // Sort the accept types acceptable to the client into order of preference then look for // a response handler that supports one of the accept types. foreach (var contentTypeWrapper in ActionInvoker.GetAcceptHeaderContentTypes(controller.RequestInfo.AcceptTypes)) { var replacementResult = NServiceMVC.Formatter.CreateContentResult(contentTypeWrapper.ContentType.ToString(), model); if (replacementResult != null) { filterContext.Result = new HttpStatusContentResult(httpStatusCode, replacementResult); filterContext.ExceptionHandled = true; return; } } } }
protected override void OnException(ExceptionContext filterContext) { String Errormsg = String.Empty; Exception unhandledException = new Exception("BASE ERROR"); if (Server.GetLastError() != null) unhandledException = Server.GetLastError(); else unhandledException = filterContext.Exception; Exception httpException = unhandledException as Exception; Errormsg = "發生例外網頁:{0}錯誤訊息:{1}"; if (httpException != null /*&& !httpException.GetType().IsAssignableFrom(typeof(HttpException))*/) { Errormsg = String.Format(Errormsg, Request.Path + Environment.NewLine,unhandledException.GetBaseException().ToString() + Environment.NewLine); Url = System.Web.HttpContext.Current.Request.Url.PathAndQuery; controller = Convert.ToString(ControllerContext.RouteData.Values["controller"]); action = Convert.ToString(ControllerContext.RouteData.Values["action"]); area = Convert.ToString(ControllerContext.RouteData.DataTokens["area"]); NLog.Logger logger = LogManager.GetCurrentClassLogger(); logger.Error(Url + "|controller|" + controller + "|action|" + action + "|area|" + area + "|" + Errormsg); } base.OnException(filterContext); filterContext.ExceptionHandled = true; }
/// <summary> /// /// </summary> /// <param name="filterContext"></param> public override void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.Exception != null) { logger.Error(filterContext.Exception); } }
public override void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null) { //If customError is Off, then AI HTTPModule will report the exception if (filterContext.HttpContext.IsCustomErrorEnabled) { string email; try { email = filterContext.HttpContext.User.Identity.Name; } catch { email = "unknown"; } var properties = new Dictionary<string, string>(); properties.Add("AzureDayUserEmail", email); // Note: A single instance of telemetry client is sufficient to track multiple telemetry items. var ai = new TelemetryClient(); ai.TrackException(filterContext.Exception, properties); } } base.OnException(filterContext); }
/// <summary> /// 处理异常,将异常保存到数据库 /// </summary> /// <param name="filterContext"></param> public void Abnormal(ExceptionContext filterContext) { MODEL.T_Abnormal abnormal = new MODEL.T_Abnormal(); string stack = filterContext.Exception.StackTrace; string[] str = stack.Split('.'); string area = str[0]; string controller = str[1]; string action = str[2]; string[] str1 = action.Split('('); string reallyaction = str1[0]; abnormal.Area = area; abnormal.Controller = controller; abnormal.ACtion = reallyaction; abnormal.Message = filterContext.Exception.Message; OperateContext.Current.BLLSession.IAbnormalBLL.Add(abnormal); //接下来在配置文件设置重定向 //注意:customErrors要放在system.web下 //string filePath = Server.MapPath("~/ExcelModel/Exception.txt"); //FileInfo file = new FileInfo(filePath); //if (!file.Exists) //{ // file.Create().Close(); //} //StreamWriter sw = System.IO.File.AppendText(filePath); }
public void ErrorResponse(string msg, ExceptionContext ec) { var routeData = new RouteValueDictionary(new { message = msg }); var response = new RedirectToRouteResult("ErrorPage", routeData); ec.Result = response; ec.ExceptionHandled = true; }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { try { //Determine the return type of the action var nameSpace = (filterContext.RouteData.DataTokens["Namespaces"] as string[]).ElementAt(0); string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType(); var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; log.ErrorFormat("[{0}.{1}]: {2}", nameSpace, actionName, filterContext.Exception.Message); log.ErrorFormat("[{0}.{1}]: {2}", nameSpace, actionName, filterContext.Exception.StackTrace); //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { var data = new { success = false, error = 10 }; filterContext.Result = new JsonResult() { Data = data }; } //If the action that generated the exception returns a view //Thank you Sumesh for the comment if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult { ViewName = "Error" }; } } catch (Exception) { log.ErrorFormat("[System]: {0}", filterContext.Exception.Message); log.ErrorFormat("[System]: {0}", filterContext.Exception.StackTrace); //If the action that generated the exception returns a view //Thank you Sumesh for the comment filterContext.Result = new ViewResult { ViewName = "Error" }; } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }
public void OnException(System.Web.Mvc.ExceptionContext filterContext) { if (!filterContext.ExceptionHandled && filterContext.Exception is IndexOutOfRangeException) { filterContext.Result = new RedirectResult("/Content/ExceptionFound.html"); filterContext.ExceptionHandled = true; } }
public void OnException(System.Web.Mvc.ExceptionContext filterContext) { //throw new NotImplementedException(); if (!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException) { filterContext.Result = new RedirectResult("Error"); filterContext.ExceptionHandled = true; } }
/// <summary> /// Adds the log. /// added by yjihrp 2012.2.3.13.08 /// modify by yjihrp 2012.2.3.13.08 /// </summary> /// <param name="filterContext">The filter context.</param> protected virtual void AddExceptionLogInfo(System.Web.Mvc.ExceptionContext filterContext) { var logType = 1; //如果说是有user的话,应该是在Session里面哦,没有则为0 var userId = 0; var pageUrl = filterContext.HttpContext.Request.Url == null ? string.Empty : filterContext.HttpContext.Request.Url.ToString(); var refUrl = filterContext.HttpContext.Request.UrlReferrer == null ? string.Empty : filterContext.HttpContext.Request.UrlReferrer.ToString(); var shortMessage = filterContext.Exception.Message; var fullMessage = filterContext.Exception.InnerException == null ? filterContext.Exception.StackTrace : filterContext.Exception.InnerException.Message; var ipAddress = Crosscutting.Function.StringHelper.GetRealIP(); iPow.Infrastructure.Data.LoggerReopsitoryManager.AddLogInfo(logType, userId, pageUrl, refUrl, shortMessage, fullMessage, ipAddress); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null) { //If customError is Off, then AI HTTPModule will report the exception if (filterContext.HttpContext.IsCustomErrorEnabled) { var ai = new CloudWatchLogger(); ai.LogError(filterContext.Exception, "AiHandleErrorAttribute"); } } base.OnException(filterContext); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null) //{ // //If customError is Off, then AI HTTPModule will report the exception // if (filterContext.HttpContext.IsCustomErrorEnabled) // { // var ai = new TelemetryClient(); // ai.TrackException(filterContext.Exception); // } //} base.OnException(filterContext); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { string actionParameterInfo; try { actionParameterInfo = GetActionParametersInfoStr(filterContext); } catch { actionParameterInfo = "参数信息:不能处理参数绑定"; } var routeValueDic = filterContext.RouteData.Values; Logger.Error("控制器:" + routeValueDic["controller"] + "/" + routeValueDic["action"] + "\r\n【参数信息】\r\n" + actionParameterInfo + "\r\n【错误详情】\r\n" + filterContext.Exception.Message); filterContext.ExceptionHandled = true; if (filterContext.RouteData.DataTokens["area"] != null) { if (filterContext.RouteData.DataTokens["area"].ToString() == "Admin") { if (filterContext.HttpContext.Request.IsAjaxRequest()) { JsonResult json = new JsonResult(); json.Data = new { Message = "出错啦" }; filterContext.Result = json; } else { // filterContext.Result = redirect; } } } else { if (filterContext.RequestContext.HttpContext.Request.Browser.IsMobileDevice) { //filterContext.Result = redirecthomepage; } else { //filterContext.Result = redirect; } } // base.OnException(filterContext); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { if (filterContext.HttpContext.IsCustomErrorEnabled) { filterContext.ExceptionHandled = true; } Dev.Log.Loger.Error(filterContext.Exception); base.OnException(filterContext); //OVERRIDE THE 500 ERROR //filterContext.HttpContext.Response.StatusCode = 200; }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { base.OnException(filterContext); //OVERRIDE THE 500 ERROR filterContext.HttpContext.Response.StatusCode = 200; var errorLog = new ErrorLog { AddedDate = System.DateTime.Now, StackTrace = filterContext.Exception.StackTrace, Message = filterContext.Exception.Message }; hopeLingerieEntities.ErrorLogs.AddObject(errorLog); hopeLingerieEntities.SaveChanges(); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { filterContext.Result = new ViewResult { ViewName = "../Error/Index" }; } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { StringBuilder lobjLogBuilder = new StringBuilder(); lobjLogBuilder.Append("Error occurred in controller action."); lobjLogBuilder.Append(string.Format("Controller-{0};", filterContext.RouteData.Values["controller"])); lobjLogBuilder.Append(string.Format("Action-{0};", filterContext.RouteData.Values["action"])); lobjLogBuilder.Append(string.Format("ExceptionMessage-{0};", filterContext.Exception.InnerException.Message)); ServerLogger.Error(lobjLogBuilder.ToString()); filterContext.ExceptionHandled = true; MessageModel msgModel = new MessageModel(MessageType.Error, ExceptionHelper.GetMessage(filterContext.Exception)); ResultDataBag lobjResult = new ResultDataBag(true, msgModel, null); filterContext.Result = new JsonResult() { Data = lobjResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; base.OnException(filterContext); }
protected override void OnException(ExceptionContext context) { // Catch invalid operation exception //if (!(context.Exception is InvalidOperationException)) return; var controllerName = context.RouteData.Values["controller"].ToString(); var actionName = context.RouteData.Values["action"].ToString(); var model = new HandleErrorInfo(context.Exception, controllerName, actionName); var result = new ViewResult { ViewName = "Error", ViewData = new ViewDataDictionary <HandleErrorInfo>(model), //Save pass the current Temp Data to the Error view, because it often contains //diagnostic information TempData = context.Controller.TempData }; Logger.Error(context.Exception.InnerException, context.Exception.Message); context.Result = result; }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { System.Exception exception = filterContext.Exception; string controller = filterContext.RouteData.Values["controller"].ToString();; string action = filterContext.RouteData.Values["action"].ToString(); if (filterContext.ExceptionHandled) { return; } else { // Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType(); var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; // If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { filterContext.Result = new JsonResult() { Data = "DATA not returned" }; } // If the action that generated the exception returns a view if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult { ViewName = "Error" }; } } // Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //Core.Cmn.AppBase.TraceViewer.Failure(filterContext.Exception.InnerException + filterContext.Exception.StackTrace + filterContext.Exception.Message); MvcExceptionInfo excepInfo = new MvcExceptionInfo(filterContext.Exception, false); //if (!this.HttpContext.User.Identity.Name.ToLower().Equals("admin")) //{ // var constantService = AppBase.DependencyInjectionManager.Resolve<Service.IConstantService>(); // var applicationFaildMsg = string.Empty; // constantService.TryGetValue<string>("ApplicationFaild", out applicationFaildMsg); // excepInfo.Message = applicationFaildMsg/*Core.Resources.ExceptionMessage.ApplicationFaild*/; // excepInfo.Details = ""; // excepInfo.IsRTL = true; //} filterContext.Result = SetException(excepInfo); filterContext.ExceptionHandled = true; _logService.Handle(filterContext.Exception, excepInfo.Message); }
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { filterContext.ExceptionHandled = true; string exceptionStr = string.Empty; try { if (filterContext.Exception != null) { exceptionStr = filterContext.Exception.StackTrace; throw filterContext.Exception; } } catch (Exception ex) { //跳转错误页 //throw ex; Response.Write(ex.Message); Response.Write(exceptionStr); } //_log.Fatal("[Error]",filterContext.Exception); }
protected virtual void OnException(ExceptionContext filterContext) { }
public void OnException(System.Web.Mvc.ExceptionContext filterContext) { base.OnException(filterContext); }
void IExceptionFilter.OnException(ExceptionContext filterContext) { OnException(filterContext); }
/// <summary> /// Called when an unhandled exception occurs in the action. /// </summary> /// <param name="filterContext">Information about the current request and action.</param> protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //AddExceptionLogInfo(filterContext); base.OnException(filterContext); }
/// <summary> /// 请求的action发生异常时会执行此方法 /// </summary> /// <param name="filterContext"></param> void System.Web.Mvc.IExceptionFilter.OnException(System.Web.Mvc.ExceptionContext filterContext) { /*//在这里你可以记录发生异常时你要干什么,比例写日志 * string message = filterContext.Exception.Message; * filterContext.Controller.ViewData["ErrorMessage"] = message; * * //返回的结果给客户端 * filterContext.Result = new System.Web.Mvc.ContentResult() * { * Content = "出错了:)", * ContentEncoding = System.Text.Encoding.UTF8 * }; * * * filterContext.ExceptionHandled = true; //告诉系统,这个异常已经处理了,不用再处理 * * //filterContext.ExceptionHandled = false; //告诉系统,这个异常没有处理,需要再处理 */ var error = filterContext.Exception; var message = error.Message;//错误信息 var msgException = typeof(MsgException); var type = filterContext.Exception.GetType(); var url = HttpContext.Current.Request.RawUrl;//错误发生地址 Console.Error.WriteLine(String.Format(url + "::" + message)); filterContext.ExceptionHandled = true; if (Constants.Debug) { filterContext.Result = new JsonResult() { ContentEncoding = Encoding.UTF8, ContentType = "application/json", Data = new HttpResp(1, message), JsonRequestBehavior = JsonRequestBehavior.AllowGet };//跳转至错误提示页面 } else { if (type.Equals(msgException)) { filterContext.Result = new JsonResult() { ContentEncoding = Encoding.UTF8, ContentType = "application/json", Data = new HttpResp(1, message), JsonRequestBehavior = JsonRequestBehavior.AllowGet };//跳转至错误提示页面 } else { filterContext.Result = new JsonResult() { ContentEncoding = Encoding.UTF8, ContentType = "application/json", Data = new HttpResp(1, "o(╥﹏╥)o 系统发生故障啦~~~"), JsonRequestBehavior = JsonRequestBehavior.AllowGet };//跳转至错误提示页面 } } }
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { this.OnException(filterContext); }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { var exception = filterContext.Exception; string controller = ""; string action = ""; bool is404 = false; if (exception.GetType() == typeof(HttpException)) { is404 = (((HttpException)exception).GetHttpCode() == 404); } controller = filterContext.RouteData.Values["controller"].ToString(); action = filterContext.RouteData.Values["action"].ToString(); if (filterContext.ExceptionHandled) { return; } else { var methodHttp = filterContext.RequestContext.HttpContext.Request.HttpMethod; var expectedAttribute = methodHttp == "POST" ? typeof(HttpPostAttribute) : null; //Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType(); var method = controllerType.GetMethods().Where(b => b.Name.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); //&& (expectedAttribute == null //|| b.GetCustomAttributes(true).Any(c => c as HttpPostAttribute != null))).FirstOrDefault(); if (!is404) { Logger.Error(String.Format("Erreur dans controlleur {0}, action {1}", filterContext.Controller.GetType().Name, actionName ), filterContext.Exception); } var returnType = method.ReturnType; var model = new HandleErrorInfo(filterContext.Exception, controllerType.Name, actionName); //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { if (is404) { filterContext.Result = new HttpNotFoundResult(); } else { filterContext.Result = new JsonResult() { Data = "Erreur interne" }; } } //If the action that generated the exception returns a view if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { if (is404) { filterContext.Result = new ViewResult { ViewName = "~/views/error/Erreur_404.cshtml" }; } else { filterContext.Result = new ViewResult { ViewName = "~/views/error/Erreur_500.cshtml", ViewData = new ViewDataDictionary(model) }; } } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { var controllerName = string.Empty; var actionName = string.Empty; if (filterContext.ExceptionHandled) { 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 { controllerName = (string)filterContext.RouteData.Values["controller"]; 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 }; } if (filterContext.Exception.GetType() != typeof(XenatixException)) { if (ApplicationSettings.EnableLogging) { var logger = EngineContext.Current.Resolve <ILogger>(); //log the error in file logger.Error(controllerName + " > " + actionName + " - " + filterContext.Exception.Message, filterContext.Exception); if (ApplicationSettings.LoggingMode == (int)LoggingMode.DataBase) { // log the error in data base ILoggingRepository loggingRepository = EngineContext.Current.Resolve <ILoggingRepository>(); loggingRepository.LogException(new ExceptionModel() { Message = filterContext.Exception.Message, Source = filterContext.Exception.Source, Comments = string.Empty }); } } } filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }
protected override void OnException(System.Web.Mvc.ExceptionContext filterContext) { NLog.LogManager.GetCurrentClassLogger().Error(filterContext.Exception, filterContext.Exception.Message); filterContext.ExceptionHandled = true; filterContext.Result = this.View("Error"); }
public void OnException(System.Web.Mvc.ExceptionContext context) { //ha szeretnénk akkor itt a kivételeket el tudjuk menteni //context.ExceptionHandled = true; }
public virtual bool InvokeAction(ControllerContext controllerContext, string actionName) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } Contract.Assert(controllerContext.RouteData != null); if ( String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch() ) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName"); } ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext); ActionDescriptor actionDescriptor = FindAction( controllerContext, controllerDescriptor, actionName ); if (actionDescriptor != null) { FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor); try { AuthenticationContext authenticationContext = InvokeAuthenticationFilters( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor ); if (authenticationContext.Result != null) { // An authentication filter signaled that we should short-circuit the request. Let all // authentication filters contribute to an action result (to combine authentication // challenges). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, authenticationContext.Result ); InvokeActionResult( controllerContext, challengeContext.Result ?? authenticationContext.Result ); } else { AuthorizationContext authorizationContext = InvokeAuthorizationFilters( controllerContext, filterInfo.AuthorizationFilters, actionDescriptor ); if (authorizationContext.Result != null) { // An authorization filter signaled that we should short-circuit the request. Let all // authentication filters contribute to an action result (to combine authentication // challenges). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, authorizationContext.Result ); InvokeActionResult( controllerContext, challengeContext.Result ?? authorizationContext.Result ); } else { if (controllerContext.Controller.ValidateRequest) { ValidateRequest(controllerContext); } IDictionary <string, object> parameters = GetParameterValues( controllerContext, actionDescriptor ); ActionExecutedContext postActionContext = InvokeActionMethodWithFilters( controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters ); // The action succeeded. Let all authentication filters contribute to an action result (to // combine authentication challenges; some authentication filters need to do negotiation // even on a successful result). Then, run this action result. AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge( controllerContext, filterInfo.AuthenticationFilters, actionDescriptor, postActionContext.Result ); InvokeActionResultWithFilters( controllerContext, filterInfo.ResultFilters, challengeContext.Result ?? postActionContext.Result ); } } } catch (ThreadAbortException) { // This type of exception occurs as a result of Response.Redirect(), but we special-case so that // the filters don't see this as an error. throw; } catch (Exception ex) { // something blew up, so execute the exception filters ExceptionContext exceptionContext = InvokeExceptionFilters( controllerContext, filterInfo.ExceptionFilters, ex ); if (!exceptionContext.ExceptionHandled) { throw; } InvokeActionResult(controllerContext, exceptionContext.Result); } return(true); } // notify controller that no method matched return(false); }