// Assumes the response headers have not been sent. If they have, still attempt to write to the body. private async Task DisplayException(HttpContext context, Exception ex) { var request = context.Request; ErrorPageModel model = new ErrorPageModel() { Options = _options, }; if (_options.ShowExceptionDetails) { model.ErrorDetails = GetErrorDetails(ex, _options.ShowSourceCode).Reverse(); } if (_options.ShowQuery) { model.Query = request.Query; }/* TODO: * if (_options.ShowCookies) * { * model.Cookies = request.Cookies; * }*/ if (_options.ShowHeaders) { model.Headers = request.Headers; }/* TODO: * if (_options.ShowEnvironment) * { * model.Environment = context; * }*/ var errorPage = new ErrorPage(model); await errorPage.ExecuteAsync(context); }
/// <summary> /// Displays an error page. /// </summary> /// <param name="context">The current HTTP context.</param> /// <param name="errorMessage">The error message.</param> /// <param name="overrideConfigSetting">if set to <c>true</c> [override config setting].</param> public void HandleError(HttpContext context, string errorMessage, bool overrideConfigSetting) { Trace.TraceData(TraceEventType.Error, "Error: " + errorMessage); Boolean showError = SAML20FederationConfig.GetConfig().ShowError; String DEFAULT_MESSAGE = "Unable to validate SAML message!"; if (!string.IsNullOrEmpty(ErrorBehaviour) && ErrorBehaviour.Equals(dk.nita.saml20.config.ErrorBehaviour.THROWEXCEPTION.ToString())) { if (showError) { throw new Saml20Exception(errorMessage); } else { throw new Saml20Exception(DEFAULT_MESSAGE); } } else { ErrorPage page = new ErrorPage(); page.OverrideConfig = overrideConfigSetting; page.ErrorText = (showError) ? errorMessage?.Replace("\n", "<br />") : DEFAULT_MESSAGE; page.ProcessRequest(context); context.Response.End(); } }
/// <summary> /// Attempts to display error page. 1st try is the current controller's TryDisplayErrorView method, 2nd try is GStore controller Error action, 3rd plan is display a static file from ErrorPages /// </summary> /// <param name="pagePath"></param> private static void ShowErrorPage(ErrorPage errorPage, int httpStatusCode, Exception ex, bool clearError, HttpContext context, BaseController controller) { if (!Settings.AppUseFriendlyErrorPages) { return; } if (controller != null) { //execute error view on controller if (TryDisplayControllerErrorView(errorPage, httpStatusCode, ex, clearError, context, controller)) { return; } } if (TryExecuteAppErrorController(errorPage, httpStatusCode, ex, clearError, context, controller)) { return; } if (TryDisplayStaticPage(errorPage, httpStatusCode, ex, clearError, context, controller)) { return; } }
public void CheckErrorResponseCode() { CustomLogs.startTestCase(System.Reflection.MethodBase.GetCurrentMethod().Name); try { HomePage homePage = HomePage; ErrorPage errorPage = homePage.ClickOnErrorBtn(); } catch (AssertFailedException afe) { CustomLogs.warn(afe.Message); throw new AssertFailedException(afe.Message); } catch (NoSuchElementException nsee) { CustomLogs.error(nsee.Message); throw new NoSuchElementException(nsee.Message); } catch (Exception exc) { CustomLogs.error(exc.Message + exc.StackTrace); throw new Exception(exc.Message); } finally { CustomLogs.endTestCase(System.Reflection.MethodBase.GetCurrentMethod().Name); } }
private void ChoicePicture_Click(object sender, RoutedEventArgs e) { try { OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true, Multiselect = false, Filter = "Images (*.jpg,*.png)|*.jpg;*.png|All Files(*.*)|*.*" }; dialog.ShowDialog(); { StrName = dialog.SafeFileName; ImageName = dialog.FileName; ImageSourceConverter isc = new ImageSourceConverter(); if (ImageName != "") { MyImage.SetValue(System.Windows.Controls.Image.SourceProperty, isc.ConvertFromString(ImageName)); // ImagePath.Text = ImageName.ToString(); } } } catch { ErrorPage Er = new ErrorPage(); Er.Show(); Er.Error_Lable.Content = "مشکلی در سیستم به وجود آمده است"; } }
public App() { try { InitializeComponent(); //Inicializo el automapper y la conexión a base de datos DatabaseHelper.InitializeAutomapper(); DatabaseHelper.CrearConexion(); //File.Delete(UsuarioActivoDTO.GetRutaRecuerdame()); if (UsuarioActivoDTO.LeerRecuerdame()) //Si devuelve true, ya esta registrado el usuario { if (UsuarioActivoDTO.IsAdmin) { MainPage = new NavigationPage(new InicioUWP()); } else { MainPage = new NavigationPage(new InicioAndroid()); } } else { MainPage = new NavigationPage(new LoginPage()); } } catch (Exception ex) { Log.Log.LogMessageToFile("Error al iniciar la aplicacion:" + ex.Message + " EN " + ex.StackTrace); MainPage = new ErrorPage(); } }
/// <summary> /// Displays an error page. /// </summary> /// <param name="context">The current HTTP context.</param> /// <param name="errorMessage">The error message.</param> /// <param name="overrideConfigSetting">if set to <c>true</c> [override config setting].</param> public void HandleError(HttpContext context, string errorMessage, bool overrideConfigSetting) { Boolean showError = SAML20FederationConfig.GetConfig().ShowError; String DEFAULT_MESSAGE = "Unable to validate SAML message!"; if (!string.IsNullOrEmpty(ErrorBehaviour) && ErrorBehaviour.Equals(com.authright.saml2.config.ErrorBehaviour.THROWEXCEPTION.ToString())) { if (showError) { throw new Saml20Exception(errorMessage); } else { throw new Saml20Exception(DEFAULT_MESSAGE); } } else { ErrorPage page = new ErrorPage(); page.OverrideConfig = overrideConfigSetting; page.ErrorText = (showError) ? errorMessage : DEFAULT_MESSAGE; page.ProcessRequest(context); context.Response.End(); } }
/// <summary> /// 刷新数据 /// </summary> /// <param name="paramant">条件</param> /// <param name="Querypage">请求页</param> /// <returns></returns> public bool GetData(object paramant, int Querypage) { object errorMsg = paramant; GetPeriodicalHistoryDAL getBingHistoryDAL = new GetPeriodicalHistoryDAL(); if (getBingHistoryDAL.GetPeriodicalHistory(ref errorMsg)) { RetrunInfo retrunInfo = errorMsg as RetrunInfo; if (retrunInfo.TrueOrFalse) { List <BingHistoryInfo> infos = retrunInfo.result as List <BingHistoryInfo>; if (infos.Count <= 0) { DataVisible = Visibility.Hidden; PICVisible = Visibility.Visible; PICState = "../Images/无数据.jpg"; return(false); } else { DataVisible = Visibility.Visible; PICVisible = Visibility.Hidden; countPage = retrunInfo.page; List <BingHistoryInfo> bingHistories = new List <BingHistoryInfo>(); int i = 1; foreach (var temp in infos) { temp.number = (Querypage - 1) * 10 + i; bingHistories.Add(temp); i++; } List = bingHistories; return(true); } } else { if (ServerSetting.IsOverDue) { ErrorPage errorPage = new ErrorPage(retrunInfo.result.ToString(), mainControl.mainWindow); DialogHelper.ShowDialog(errorPage); return(false); } else { DataVisible = Visibility.Hidden; PICVisible = Visibility.Visible; PICState = "../Images/未连接.png"; return(false); } } } else { DataVisible = Visibility.Hidden; PICVisible = Visibility.Visible; PICState = "../Images/未连接.png"; return(false); } }
public ErrorSteps(IWebDriver driver, ExtentTest test, ScenarioContext scenarioContext) { _driver = driver; _test = test; _scenarioContext = scenarioContext; _commonPage = new CommonPage(_driver, _test); _errorPage = new ErrorPage(_driver, _test, _commonPage); }
public ContactFormSteps(IWebDriver driver, HomePage homePage, ContactFormPage contactFormPage, ErrorPage errorPage, SearchResultsPage searchResultsPage) { this.homePage = homePage; this.contactFormPage = contactFormPage; this.errorPage = errorPage; this.searchResultsPage = searchResultsPage; }
private void displayError(string service, string message) { window.Dispatcher.BeginInvoke((Action)(() => { ErrorPage page = new ErrorPage(service, message); window.NavigationService.Navigate(page); window.isInHelpPage = false; })); }
/// <summary> /// Startup hooks are pieces of code that will run before a users program main executes /// See: https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/host-startup-hook.md /// </summary> public static void Initialize() { if (!NativeMethods.IsAspNetCoreModuleLoaded()) { // This means someone set the startup hook for Microsoft.AspNetCore.Server.IIS // but are not running inprocess. Return at this point. return; } var detailedErrors = Environment.GetEnvironmentVariable("ASPNETCORE_DETAILEDERRORS"); var enableStartupErrorPage = detailedErrors?.Equals("1", StringComparison.OrdinalIgnoreCase) ?? false; enableStartupErrorPage |= detailedErrors?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false; var aspnetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); enableStartupErrorPage |= aspnetCoreEnvironment?.Equals("Development", StringComparison.OrdinalIgnoreCase) ?? false; var dotnetEnvironment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT"); enableStartupErrorPage |= dotnetEnvironment?.Equals("Development", StringComparison.OrdinalIgnoreCase) ?? false; if (!enableStartupErrorPage) { // Not running in development or detailed errors aren't enabled return; } AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { var exception = (Exception)eventArgs.ExceptionObject; // Get the content root from IIS. var iisConfigData = NativeMethods.HttpGetApplicationProperties(); var contentRoot = iisConfigData.pwzFullApplicationPath.TrimEnd(Path.DirectorySeparatorChar); var model = ErrorPageModelBuilder.CreateErrorPageModel( new PhysicalFileProvider(contentRoot), logger: null, showDetailedErrors: true, exception); var errorPage = new ErrorPage(model); var stream = new MemoryStream(); // Never will go async because we are writing to a memory stream. errorPage.ExecuteAsync(stream).GetAwaiter().GetResult(); // Get the raw content and set the error page. stream.Position = 0; var content = stream.ToArray(); NativeMethods.HttpSetStartupErrorPageContent(content); }; }
public void OrderingATicketToTheSameStation() { mainPage.InputCityFromAndCityTo("Manchester Victoria", "Manchester Victoria") .InputDateDefaultValues() .SetAdultsAndChildren(1, 0) .Submit(); ErrorPage error = new ErrorPage(driver); Assert.AreEqual(secondErrorMessage, error.errorMessage.Text); }
public void Index_WhenPassingPage_ShouldUseItOnModel() { // Arrange var errorPage = new ErrorPage(); // Act var result = (ViewResult)_subject.Index(errorPage); // Assert Assert.AreEqual <ErrorPage>(errorPage, ((ErrorViewModel)result.Model).CurrentPage); }
public GStoreErrorInfo(ErrorPage errorPage, Exception exception, RouteData routeData, string controllerName, string actionName, string ipAddress, Models.StoreFront currentstoreFrontOrNull, string rawUrl, string url) : base(exception, controllerName, actionName) { this.ErrorPage = errorPage; this.ErrorCode = (int)errorPage; this.RouteDataSource = routeData.ToSourceString(); this.IPAddress = ipAddress; this.CurrentstoreFrontOrNull = currentstoreFrontOrNull; this.RawUrl = rawUrl; this.Url = url; }
private Task DisplayRuntimeException(HttpContext context, Exception ex) { var endpoint = context.GetEndpoint(); EndpointModel?endpointModel = null; if (endpoint != null) { endpointModel = new EndpointModel(); endpointModel.DisplayName = endpoint.DisplayName; if (endpoint is RouteEndpoint routeEndpoint) { endpointModel.RoutePattern = routeEndpoint.RoutePattern.RawText; endpointModel.Order = routeEndpoint.Order; var httpMethods = endpoint.Metadata.GetMetadata <IHttpMethodMetadata>()?.HttpMethods; if (httpMethods != null) { endpointModel.HttpMethods = string.Join(", ", httpMethods); } } } var request = context.Request; var title = Resources.ErrorPageHtml_Title; if (ex is BadHttpRequestException badHttpRequestException) { var badRequestReasonPhrase = WebUtilities.ReasonPhrases.GetReasonPhrase(badHttpRequestException.StatusCode); if (!string.IsNullOrEmpty(badRequestReasonPhrase)) { title = badRequestReasonPhrase; } } var model = new ErrorPageModel { Options = _options, ErrorDetails = _exceptionDetailsProvider.GetDetails(ex), Query = request.Query, Cookies = request.Cookies, Headers = request.Headers, RouteValues = request.RouteValues, Endpoint = endpointModel, Title = title, }; var errorPage = new ErrorPage(model); return(errorPage.ExecuteAsync(context)); }
private RequestDelegate BuildErrorPageApplication(Exception exception) { if (exception is TargetInvocationException tae) { exception = tae.InnerException; } var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors; var model = new ErrorPageModel { RuntimeDisplayName = RuntimeInformation.FrameworkDescription }; var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).Assembly; var assemblyVersion = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString(); var clrVersion = assemblyVersion; model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString(); var currentAssembly = typeof(ErrorPage).Assembly; model.CurrentAssemblyVesion = currentAssembly .GetCustomAttribute <AssemblyInformationalVersionAttribute>() .InformationalVersion; model.ClrVersion = clrVersion; model.OperatingSystemDescription = RuntimeInformation.OSDescription; model.ShowRuntimeDetails = showDetailedErrors; if (showDetailedErrors) { var exceptionDetailProvider = new ExceptionDetailsProvider( HostingEnvironment.ContentRootFileProvider, Logger, sourceCodeLineCount: 6); model.ErrorDetails = exceptionDetailProvider.GetDetails(exception); } else { model.ErrorDetails = Array.Empty <ExceptionDetails>(); } var errorPage = new ErrorPage(model); return(context => { context.Response.StatusCode = 500; context.Response.Headers[HeaderNames.CacheControl] = "no-cache,no-store"; context.Response.Headers[HeaderNames.Pragma] = "no-cache"; context.Response.ContentType = "text/html; charset=utf-8"; return errorPage.ExecuteAsync(context); }); }
public void WhenINavigateToEachPage() { pageTitles.Add("home page", homePage.GetTitle()); pageLogos.Add("home page", homePage.IsCompanyLogoPresent()); formPage = homePage.OpenFormPage(); pageTitles.Add("form page", formPage.GetTitle()); pageLogos.Add("form page", formPage.IsCompanyLogoPresent()); errorPage = formPage.OpenErrorPage(); pageTitles.Add("error page", errorPage.GetTitle()); pageLogos.Add("error page", errorPage.IsCompanyLogoPresent()); }
public App() { InitializeComponent(); InternetConnection connection = new InternetConnection(); if (connection.CheckConnection()) { MainPage = new MainPage(); } else { MainPage = new ErrorPage(); } }
/// <summary> /// Displays an error page. /// </summary> /// <param name="context">The current HTTP context.</param> /// <param name="errorMessage">The error message.</param> /// <param name="overrideConfigSetting">if set to <c>true</c> [override config setting].</param> public void HandleError(HttpContext context, string errorMessage, bool overrideConfigSetting) { if (!string.IsNullOrEmpty(ErrorBehaviour) && ErrorBehaviour.Equals(dk.nita.saml20.config.ErrorBehaviour.THROWEXCEPTION.ToString())) { throw new Saml20Exception(errorMessage); } else { ErrorPage page = new ErrorPage(); page.OverrideConfig = overrideConfigSetting; page.ErrorText = errorMessage; page.ProcessRequest(context); context.Response.End(); } }
public static void RedirectToErrorPage(HttpServletResponse res, Exception e, string path, bool devMode) { string st = devMode ? ErrorPage.ToStackTrace(e, 1024 * 3) : "See logs for stack trace"; // spec: min 4KB res.SetStatus(res.ScFound); Cookie cookie = new Cookie(StatusCookie, 500.ToString()); cookie.SetPath(path); res.AddCookie(cookie); cookie = new Cookie(ErrorCookie, st); cookie.SetPath(path); res.AddCookie(cookie); res.SetHeader("Location", path); }
/// <summary> /// Funzione per navigare alla pagina di errore /// </summary> public static void NavigateToErrorPage(ErrorCode errorCode, string description, bool endResponse) { try { string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower(); if (!absoluteUri.Contains("errorpage")) { ErrorPage.SetErrorDescription(errorCode, description); HttpContext.Current.Response.Redirect("~/ErrorPage.aspx", endResponse); } } catch (Exception ex) { Log.Error(ex, ex.Message); throw; } }
RequestDelegate BuildErrorPageApplication(Exception exception) { if (exception is TargetInvocationException tae) { exception = tae.InnerException; } var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.GameHostOptions.DetailedErrors; var model = new ErrorPageModel { RuntimeDisplayName = RuntimeInformation.FrameworkDescription }; var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).GetTypeInfo().Assembly; var assemblyVersion = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString(); var clrVersion = assemblyVersion; model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString(); var currentAssembly = typeof(ErrorPage).GetTypeInfo().Assembly; model.CurrentAssemblyVesion = currentAssembly .GetCustomAttribute <AssemblyInformationalVersionAttribute>() .InformationalVersion; model.ClrVersion = clrVersion; model.OperatingSystemDescription = RuntimeInformation.OSDescription; //if (showDetailedErrors) //{ // var exceptionDetailProvider = new ExceptionDetailsProvider( // HostingEnvironment.ContentRootFileProvider, // sourceCodeLineCount: 6); // model.ErrorDetails = exceptionDetailProvider.GetDetails(exception); //} //else // model.ErrorDetails = new ExceptionDetails[0]; var errorPage = new ErrorPage(model); return(context => { context.Response.StatusCode = 500; context.Response.Headers["Cache-Control"] = "no-cache"; return errorPage.ExecuteAsync(context); }); }
//[Test] public void TheTestClass() { driver.Navigate().GoToUrl(baseURL + "/"); driver.Manage().Window.Maximize(); HomePage home = new HomePage(driver); home.InspectHomePages(); FormPage form = new FormPage(driver); form.InspectFormPage(); ErrorPage error = new ErrorPage(driver); error.InspectErrorPage(); }
private Task DisplayRuntimeException(HttpContext context, Exception ex) { var request = context.Request; var model = new ErrorPageModel { Options = _options, ErrorDetails = _exceptionDetailsProvider.GetDetails(ex), Query = request.Query, Cookies = request.Cookies, Headers = request.Headers }; var errorPage = new ErrorPage(model); return(errorPage.ExecuteAsync(context)); }
private PageViewModel CreateInstance(Type pageViewModelType) { PageViewModel instance; try { instance = (PageViewModel)Activator.CreateInstance(pageViewModelType, Context); } catch (Exception ex) { Core.Log.HandleUnexpectedException(ex, false); instance = ErrorPage.Instantiate(Context); } _instances.Add(pageViewModelType, instance); return(instance); }
public void GetData() { object errorMsg = ServerSetting.parament; SelectListDAL selectListDAL = new SelectListDAL(); bool flag = selectListDAL.SelectList(ServerSetting.@class, ref errorMsg); if (flag) { RetrunInfo info = errorMsg as RetrunInfo; List <QueryInfo> Lists = info.result as List <QueryInfo>; bool flag2 = Lists.Count > 0; if (flag2) { this.PICVisible = Visibility.Hidden; this.DataVisible = Visibility.Visible; ServerSetting.info = Lists; this.List = Lists; this.LoadPage = ServerSetting.loadPage.ToString(); } else { this.PICVisible = Visibility.Visible; this.PICState = new BitmapImage(new Uri("../Images/������.jpg", UriKind.RelativeOrAbsolute)); this.DataVisible = Visibility.Hidden; ServerSetting.totalPages = 0; ServerSetting.List = null; ServerSetting.loadPage = 1; ServerSetting.info = null; } } else { this.PICVisible = Visibility.Visible; this.PICState = new BitmapImage(new Uri("../Images/���.png", UriKind.RelativeOrAbsolute)); this.DataVisible = Visibility.Hidden; bool isOverDue = ServerSetting.IsOverDue; if (isOverDue) { RetrunInfo info2 = errorMsg as RetrunInfo; ErrorPage errorPage = new ErrorPage(info2.result.ToString(), this.control.mainWindow); DialogHelper.ShowDialog(errorPage); } } }
public void OpenCloudPanel() { if (CloudPanel.activeInHierarchy) { CloudPanel.SetActive(false); return; } if (!CheckStatusError()) { ErrorPage.SetActive(true); } else { ErrorPage.SetActive(false); ProjectNameText.text = LimSystem.ChartContainer.ChartProperty.ChartName; StartCoroutine(GetLastModifyTime()); } CloudPanel.SetActive(true); }
private Task DisplayRuntimeException(HttpContext context, Exception ex) { var endpoint = context.Features.Get <IEndpointFeature>()?.Endpoint; EndpointModel endpointModel = null; if (endpoint != null) { endpointModel = new EndpointModel(); endpointModel.DisplayName = endpoint.DisplayName; if (endpoint is RouteEndpoint routeEndpoint) { endpointModel.RoutePattern = routeEndpoint.RoutePattern.RawText; endpointModel.Order = routeEndpoint.Order; var httpMethods = endpoint.Metadata.GetMetadata <IHttpMethodMetadata>()?.HttpMethods; if (httpMethods != null) { endpointModel.HttpMethods = string.Join(", ", httpMethods); } } } var request = context.Request; var model = new ErrorPageModel { Options = _options, ErrorDetails = _exceptionDetailsProvider.GetDetails(ex), Query = request.Query, Cookies = request.Cookies, Headers = request.Headers, RouteValues = request.RouteValues, Endpoint = endpointModel }; var errorPage = new ErrorPage(model); return(errorPage.ExecuteAsync(context)); }
public App() { InitializeComponent(); TimeManager.SetCurrentTimes(); if (CrossConnectivity.Current.IsConnected) { if (!StudentInfoModel.GetLoginInfo()) { MainPage = new LoginPage(); } else { MainPage = new ScheduleNavigationPage(new ScheduleView(StudentInfoModel.YearFormation, StudentInfoModel.Group, StudentInfoModel.Subgroup)); } } else { MainPage = new ErrorPage(); } }
public static bool TryDisplayControllerErrorView(ErrorPage errorPage, int httpStatusCode, Exception ex, bool clearError, HttpContext context, BaseController controller) { string url = string.Empty; string rawUrl = string.Empty; if (context != null) { url = context.Request.Url.ToString(); rawUrl = context.Request.RawUrl; } try { if (controller == null) { return false; } System.Diagnostics.Trace.WriteLine("--Executing controller.TryDisplayErrorView for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); bool resultSuccess = controller.TryDisplayErrorView(ex, errorPage, httpStatusCode, false); System.Diagnostics.Trace.WriteLine("--" + (resultSuccess ? "Success" : "Failure") + " executing controller.TryDisplayErrorView. Result: " + resultSuccess.ToString() + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); if (resultSuccess) { if (clearError) { context.ClearError(); } return true; } return false; } catch (Exception exController) { System.Diagnostics.Trace.WriteLine("--Error executing controller.TryDisplayErrorView for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Exception: " + exController.Message + " Original Exception: " + ex.Message); return false; } }
public static bool TryDisplayStaticPage(ErrorPage errorPage, int httpStatusCode, Exception ex, bool clearError, HttpContext context, BaseController controller) { string url = string.Empty; string rawUrl = string.Empty; if (context != null) { url = context.Request.Url.ToString(); rawUrl = context.Request.RawUrl; } if (controller != null && controller.CurrentStoreFrontOrNull != null) { //start with storefront error pages folder Models.StoreFront storeFront = controller.CurrentStoreFrontOrThrow; string customErrorFolder = storeFront.StoreFrontVirtualDirectoryToMap(controller.Request.ApplicationPath) + "/ErrorPages/"; string customErrorPath = customErrorFolder + errorPage.ErrorPageFileName(); bool customErrorFileExists = false; if (System.IO.File.Exists(context.Server.MapPath(customErrorPath))) { customErrorFileExists = true; } else { //if store front error page not found, look for client custom error page customErrorFolder = storeFront.Client.ClientVirtualDirectoryToMap(context.Request.ApplicationPath) + "/ErrorPages/"; customErrorPath = customErrorFolder + errorPage.ErrorPageFileName(); if (System.IO.File.Exists(context.Server.MapPath(customErrorPath))) { customErrorFileExists = true; } } if (customErrorFileExists) { try { context.Response.Clear(); context.Response.StatusCode = httpStatusCode; System.Diagnostics.Trace.WriteLine("--Displaying custom error static page: " + customErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); context.Server.Execute(customErrorPath); context.Response.Flush(); System.Diagnostics.Trace.WriteLine("--Success displaying custom error static page: " + customErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); if (clearError) { context.ClearError(); } return true; } catch (Exception exCustomPageError) { System.Diagnostics.Trace.WriteLine("--Failure. Error displaying custom error static page: " + customErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Exception: " + exCustomPageError.Message + " Original Exception: " + ex.Message); string error = exCustomPageError.Message; } } } //unknown client or client does not have a custom error page, show server static error page string serverErrorFolder = "~/Content/Server/ErrorPages/"; string serverErrorPath = serverErrorFolder + errorPage.ErrorPageFileName(); if (!System.IO.File.Exists(context.Server.MapPath(serverErrorPath))) { System.Diagnostics.Trace.WriteLine("--Failure. Error: Server error static page not found: " + serverErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); return false; } try { context.Response.Clear(); context.Response.StatusCode = httpStatusCode; System.Diagnostics.Trace.WriteLine("--Displaying server error static page: " + serverErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl); context.Server.Execute(serverErrorPath); context.Response.Flush(); System.Diagnostics.Trace.WriteLine("--Success displaying server error static page: " + serverErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl); if (clearError) { context.Server.ClearError(); } return true; } catch (Exception exServerPageError) { System.Diagnostics.Trace.WriteLine("--Failure. Error displaying server error static page: " + serverErrorPath + " for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Exception: " + exServerPageError.Message + " Original Exception: " + ex.Message); return false; } }
/// <summary> /// Executes the GStore controller with an error view. controller must be set /// </summary> /// <param name="errorPage"></param> /// <param name="httpStatusCode"></param> /// <param name="ex"></param> /// <param name="clearError"></param> /// <param name="context"></param> /// <param name="controller"></param> /// <returns></returns> public static bool TryExecuteAppErrorController(ErrorPage errorPage, int httpStatusCode, Exception ex, bool clearError, HttpContext context, BaseController controller) { string url = string.Empty; string rawUrl = string.Empty; if (context != null) { url = context.Request.Url.ToString(); rawUrl = context.Request.RawUrl; } if (controller == null) { System.Diagnostics.Trace.WriteLine("--Failure. Controller is null; no error controller is available ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); return false; } var routeData = new RouteData(); //if we can find the current area from the url, we can use a area-specific error handler to incorporate area layout/design string area = context.Request.DetermineAreaFromRequest(); if (!string.IsNullOrEmpty(area)) { routeData.DataTokens.Add("area", area); } routeData.Values["controller"] = "GStore"; routeData.Values["action"] = "AppError"; routeData.Values["exception"] = ex; routeData.Values["errorpage"] = errorPage; routeData.Values["httpStatusCode"] = httpStatusCode; System.Web.Mvc.IController errorController = null; if (controller != null) { try { errorController = controller.GStoreErrorControllerForArea; } catch (Exception exAreaError) { System.Diagnostics.Trace.WriteLine("--Failure. Error getting GStoreErrorControllerForArea for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Exception: " + exAreaError.Message + " Original Exception: " + ex.Message); return false; } } var rc = new RequestContext(new HttpContextWrapper(context), routeData); try { System.Diagnostics.Trace.WriteLine("--Executing error controller for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); errorController.Execute(rc); System.Diagnostics.Trace.WriteLine("--Success executing error controller for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Original Exception: " + ex.Message); if (clearError) { context.ClearError(); } return true; } catch (Exception exErrorController) { System.Diagnostics.Trace.WriteLine("--Failure. Error executing error controller for ErrorPage: " + errorPage.ToString() + " Url: " + url + " RawUrl: " + rawUrl + " Exception: " + exErrorController.Message + " Original Exception: " + ex.Message); return false; } }