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; }
/// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="httpapplication">The http application.</param> /// <param name="httpexception">The http exception.</param> private static void ApplicationOnErrorFilter(HttpApplication httpapplication, HttpException httpexception) { // Modify if need try { if (httpexception != null) { switch ((HttpStatusCode)httpexception.GetHttpCode()) { case HttpStatusCode.InternalServerError: // Error caused by Search engine caching of ASP.NET assembly WebResource.axd file(s) // 'WebResource.axd' Or 'ScriptResource.axd' string url = httpapplication.Context.Request.Url.AbsolutePath; if (url.EndsWith(".axd", StringComparison.OrdinalIgnoreCase)) { httpapplication.Context.Server.ClearError(); } break; } } } catch (Exception ex) { // CRITICAL: Error Log must not throw unhandled errors Logger.InfoException(ex.Message, ex); } }
protected void Application_Error() { if (HttpContext.Current == null) { // errors in Application_Start will end up here return; } if (HttpContext.Current.IsCustomErrorEnabled) { return; } var exception = Server.GetLastError(); var httpException = new HttpException(null, exception); if (httpException.GetHttpCode() == 404 && WebHelper.IsStaticResource(this.Request)) { return; } //TODO: 记录Log(忽略404,403) var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("httpException", httpException); Server.ClearError(); // Call target Controller and pass the routeData. //Ref nop&nblog IController errorController = SDFEngine.Container.Resolve<ErrorController>(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); }
protected void Application_Error() { // Log ASP.NET errors (404, 500) HttpException exception = new HttpException(null, HttpContext.Current.Server.GetLastError()); Log.Error("An ASP.NET based error occurred - ({0}) - {1}", exception.GetHttpCode(), exception.ToString()); }
private RouteData GetErrorRouteData(HttpException httpException, CustomErrorsSection config) { var statusCode = httpException.GetHttpCode().ToString(CultureInfo.InvariantCulture); var routeData = RouteInfo.GetRouteDataByUrl(config.Errors[statusCode] != null ? config.Errors[statusCode].Redirect : config.DefaultRedirect); return routeData; }
public void Increment_WithHttpExceptionThatIsNot404_AddsStatusCodeToReadingName() { var sensor = new ExceptionSensor(); var exception = new HttpException(500, "Page not found"); sensor.AddError(exception); Reading reading = null; ReadingPublisher.Readings.TryDequeue(out reading); // TotalExceptions ReadingPublisher.Readings.TryDequeue(out reading); Assert.That(reading.Data.Name, Is.EqualTo(exception.GetHttpCode() + exception.GetType().Name )); }
protected void Page_Load(object sender, EventArgs e) { ex = (HttpException)Server.GetLastError(); int httpCode = ex.GetHttpCode(); // Filter for Error Codes and set text if (httpCode == 401) ex = new HttpException (httpCode, "Request Unauthorized!", ex); else if (httpCode == 403) ex = new HttpException (httpCode, "Forbidden Request!",ex); else if (httpCode >= 400 && httpCode < 500) ex = new HttpException (httpCode, "File not found!", ex); else if (httpCode > 499) ex = new HttpException (ex.ErrorCode, "Oops...! :(", ex); else ex = new HttpException (httpCode, "Unexpected Exception!", ex); // Log the exception and notify system operators ExceptionUtility.LogException(ex, "HttpErrorPage"); ExceptionUtility.NotifySystemOps(ex); // Fill the page fields exCode.Text = httpCode.ToString(); exMessage.Text = ex.Message; exTrace.Text = ex.StackTrace; // Show Inner Exception fields for local access if (ex.InnerException != null) { innerTrace.Text = ex.InnerException.StackTrace; InnerErrorPanel.Visible = Request.IsLocal; innerMessage.Text = string.Format("HTTP {0}: {1}", httpCode, ex.InnerException.Message); } // Show Trace for local access exTrace.Visible = Request.IsLocal; // Clear the error from the server Server.ClearError(); }
private void Application_OnError(object sender, System.EventArgs e) { System.Web.HttpApplication httpApplication = (System.Web.HttpApplication)sender; System.Web.HttpContext context = httpApplication.Context; System.Exception ex = context.Server.GetLastError(); if (ex is System.Web.HttpException) { System.Web.HttpException ex2 = ex as System.Web.HttpException; if (ex2.GetHttpCode() == 404) { string arg_41_0 = httpApplication.Request.PhysicalPath; TextLogger.Write(string.Format("文件不存在:{0}", httpApplication.Request.Url.AbsoluteUri)); return; } } if (ex.InnerException != null) { ex = ex.InnerException; } System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder().AppendFormat("访问路径:{0}", GameRequest.GetRawUrl()).AppendLine().AppendFormat("{0} thrown {1}", ex.Source, ex.GetType().ToString()).AppendLine().Append(ex.Message).Append(ex.StackTrace); TextLogger.Write(stringBuilder.ToString()); }
private bool ShouldHandle(ExceptionContext filterContext) { if (filterContext.IsChildAction) { return false; } if (filterContext.ExceptionHandled) { return false; } var exception = filterContext.Exception; var httpException = new HttpException(null, exception); var httpExceptionHttpCode = httpException.GetHttpCode(); if (httpExceptionHttpCode != 500) { return false; } return this.ExceptionType.IsInstanceOfType(exception); }
protected void Page_Load(object sender, EventArgs e) { ex = (HttpException)Server.GetLastError(); int httpCode = ex.GetHttpCode(); // Filter for Error Codes and set text if (httpCode >= 400 && httpCode < 500) ex = new HttpException (httpCode, "Safe message for 4xx HTTP codes.", ex); else if (httpCode > 499) ex = new HttpException (ex.ErrorCode, "Safe message for 5xx HTTP codes.", ex); else ex = new HttpException (httpCode, "Safe message for unexpected HTTP codes.", ex); // Log the exception and notify system operators ISTATRegistry.Classes.ExceptionUtility.LogException(ex, "HttpErrorPage"); //ExceptionUtility.NotifySystemOps(ex); // Fill the page fields exMessage.Text = ex.Message; exTrace.Text = ex.StackTrace; // Show Inner Exception fields for local access if (ex.InnerException != null) { innerTrace.Text = ex.InnerException.StackTrace; InnerErrorPanel.Visible = true; innerMessage.Text = string.Format("HTTP {0}: {1}", httpCode, ex.InnerException.Message); } // Clear the error from the server Server.ClearError(); }
/// <summary> /// Sends back a response using the status code in the HttpException. /// The response body contains a details serialized in the responseFormat. /// If the HttpException.Data has a key named "details", its value is used as the response body. /// If there is no such key, HttpException.ToString() is used as the response body. /// </summary> /// <param name="httpException"></param> /// <param name="responseFormat"></param> public ResourceErrorActionResult(HttpException httpException, ContentType responseFormat) { this.statusCode = (HttpStatusCode)httpException.GetHttpCode(); this.details = httpException.Data.Contains("details") ? httpException.Data["details"] : httpException.ToString(); this.responseFormat = responseFormat; }
public static void SendErrorResponse(HttpResponseBase response, System.Web.HttpException he, string moduleVersion) { int httpStatusCode = he.GetHttpCode(); string msgType = StatusCodeMessage(httpStatusCode); string errorDoc = null; try { errorDoc = Utilities.GetXmlStringFromFile(Settings.Get(("ErrorTemplate"))); } catch (Exception ex) { // use default template if we can't find the requested one if (string.IsNullOrEmpty(errorDoc)) { errorDoc = "<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE html PUBLIC \"-/W3C/DTD XHTML 1.0 Transitional/EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns = \"http:/www.w3.org/1999/xhtml\"><head><title>Application Error - {0} {1}</title></head><body style=\"font-family:Arial; font-size:10pt; color:#330000\"><h1>{0} {1}</h1><div class=\"error_message\">{2}</div><b><span class=\"error_location\">{4}.{3}</span></b><!--\n{5}\n--><br/><br/>In addition, the error page could not be loaded, so this default page was used instead.\n<!--THE FOLLOWING EXCEPTION OCCURRED WHILE LOADING THE ERROR TEMPLATE:\n" + ex.Message + "\n--><hr/><i>RestNet Application {6}</i></body></html>"; } } var url = (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null) ? string.Format(" ({0})", HttpContext.Current.Request.Headers["X-REWRITE-URL"] ?? HttpContext.Current.Request.Url.PathAndQuery) : string.Empty; System.Reflection.MethodBase targetSite = he.GetBaseException().TargetSite; string msg = string.Format(errorDoc, httpStatusCode, msgType, he.Message + url, targetSite == null ? string.Empty : targetSite.Name, targetSite == null ? string.Empty : targetSite.ReflectedType.FullName, System.Web.HttpUtility.HtmlEncode(he.GetBaseException().StackTrace), moduleVersion); // Set logging level differently for client vs. server errors. // 100, 200, 300 series should never really appear, but just in case I've included them here // also, don't bother including full exceptions for < 500, as they're likely to just duplicate the message switch ((int)(httpStatusCode / 100)) { case 0: case 1: case 2: Logging.Debug(he.Message + url); break; case 3: Logging.InfoFormat("{0} - {1}", httpStatusCode, he.Message + url); break; case 4: if (httpStatusCode == 401) { // 401 challenge isn't really worthy of a warning Logging.DebugFormat("{0} - {1}", httpStatusCode, he.Message + url); } else { Logging.WarnFormat("{0} - {1}", httpStatusCode, he.Message + url); } break; default: Logging.Error(string.Format("{0} - {1}", httpStatusCode, he.Message + url), he); break; } ReturnError(response, httpStatusCode, msg); }
public void OnException(ExceptionContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.IsChildAction) { return; } //NOTE: I used to check for custom errors enabled but then realized that we 'never' really // want to see a YSOD instead of being redirected to the installer or the not authorized page. //if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) // return; if (filterContext.ExceptionHandled) return; var exception = filterContext.Exception; var httpException = new HttpException(null, exception); if (httpException.GetHttpCode() != (int)global::System.Net.HttpStatusCode.Forbidden && httpException.GetHttpCode() != (int)global::System.Net.HttpStatusCode.Unauthorized) { //ignore if not 403 or 401 return; } switch (httpException.GetHttpCode()) { case (int)global::System.Net.HttpStatusCode.Unauthorized: //The user could not login object routeVals; if (_showLoginOverlay) { routeVals = new { area = "Umbraco", action = "Login", controller = "Default", ReturnUrl = filterContext.HttpContext.Request.Url.PathAndQuery, displayType = LoginDisplayType.ShowOverlay }; } else { //since we're not displaying the overlay, we wont include the other route val, makes urls nicer routeVals = new { area = "Umbraco", action = "Login", controller = "Default", ReturnUrl = filterContext.HttpContext.Request.Url.PathAndQuery }; } //redirect to login filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary(routeVals)); break; case (int)global::System.Net.HttpStatusCode.Forbidden: //The user does not have access to the resource, show the insufficient priviledges view //need to update the route values so that Login returns the correct view var defaultController = new DefaultController(BackOfficeRequestContext); filterContext.RouteData.Values["Action"] = "InsufficientPermissions"; filterContext.RouteData.Values["Controller"] = "Default"; filterContext.HttpContext.Response.StatusCode = (int)global::System.Net.HttpStatusCode.Forbidden; filterContext.Result = defaultController.InsufficientPermissions(filterContext.HttpContext.Request.Url.PathAndQuery); break; } filterContext.ExceptionHandled = true; //NOTE: Due to the way the FormsAuthenticationModule in ASP.Net works, specifically in it's OnLeave method // it specifically checks for a 401 status code, changes it to a 301 and redirects to the FormsAuthentication.LoginUrl // which can only be set singly meaning that you can't have 2 different login URLs even when using the 'location' // element in your web.config. Hopefully MS fixes this in future versions of .Net. In the meantime we have 2 options: // - Don't return a 401 Http status code // - Hijack the Application_EndRequest to detect that we wanted to render a 401 and change it to 401 which is kinda ugly. // so, we're just not going to return a 401 status code. //filterContext.HttpContext.Response.StatusCode = httpException.GetHttpCode(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }
private static void LogHttpException(HttpException ex, HttpContext context, RouteData routeData, BaseController controller) { int httpCode = ex.GetHttpCode(); string message = string.Empty; if (httpCode == 404) { LogFileNotFound(ex, context, routeData, controller); return; } if ((httpCode == 400) && (routeData != null)) { //if 400 came from a controller, handle it in the bad request log, not system (error) log LogBadRequest(ex, context, routeData, controller); return; } message = "Http Exception " + httpCode + " " + ex.GetHtmlErrorMessage() + " \n-Message: " + ex.Message + " \n-Source: " + ex.Source + " \n-WebEventCode: " + ex.WebEventCode + " \n-ErrorCode: " + ex.ErrorCode + " \n-TargetSiteName: " + ex.TargetSite.Name + " \n-StackTrace: " + ex.StackTrace; LogException(message, ex, Models.SystemEventLevel.Error, context, routeData, controller); }
public static bool HandleHttpException(HttpException ex, bool clearError, HttpContext context, RouteData routeData, BaseController controller) { string rawUrl = context.Request.RawUrl; string url = context.Request.Url.ToString(); if (Settings.AppLogSystemEventsToDb || Settings.AppLogSystemEventsToFile) { LogHttpException(ex, context, routeData, controller); } int httpCode = ex.GetHttpCode(); if (httpCode == 404) { if (Settings.AppUseFriendlyErrorPages) { ShowErrorPage(ErrorPage.Error_NotFound, ex.GetHttpCode(), ex, clearError, context, controller); return true; } return false; } else if (httpCode == 400) { if (Settings.AppUseFriendlyErrorPages) { ShowErrorPage(ErrorPage.Error_BadRequest, ex.GetHttpCode(), ex, clearError, context, controller); return true; } return false; } else { //unhandled HTTP code if (Settings.AppUseFriendlyErrorPages) { ShowErrorPage(ErrorPage.Error_HttpError, ex.GetHttpCode(), ex, clearError, context, controller); return true; } return false; } }
public void Constructor2b_Deny_Unrestricted () { HttpException e = new HttpException ("message", new Exception ()); e.GetHtmlErrorMessage (); // null for ms, non-null for mono Assert.AreEqual (500, e.GetHttpCode (), "HttpCode"); }
/// <summary> /// Initializes a new instance of the <see cref="VLogServerSideError"/> class. /// from a given <see cref="HttpException"/> instance and /// <see cref="HttpContext"/> instance representing the HTTP /// context during the exception. /// </summary> /// <param name="httpexception">The occurred server side exception</param> public VLogServerSideError(HttpException httpexception) : this() { HttpContext context = HttpContext.Current; if (httpexception != null && context != null) { this.ErrorMessage = httpexception.GetErrorMessage(); this.ErrorDetails = httpexception.GetErrorErrorDetails(); // Sets an object of a uniform resource identifier properties this.SetAdditionalHttpContextInfo(context); this.SetAdditionalExceptionInfo(httpexception); // If this is an HTTP exception, then get the status code // and detailed HTML message provided by the host. this.ErrorCode = httpexception.GetHttpCode(); VLogErrorCode errorcoderule; if (VLog.WebErrorCodes.TryGetValue(this.ErrorCode, out errorcoderule) && !errorcoderule.ExcludeFromLogging) { this.AddHttpExceptionData(errorcoderule, context, httpexception, errorcoderule); } } }
static void FinishWithException (HttpWorkerRequest wr, HttpException e) { int code = e.GetHttpCode (); wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code)); wr.SendUnknownResponseHeader ("Connection", "close"); Encoding enc = Encoding.ASCII; wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName); string msg = e.GetHtmlErrorMessage (); byte [] contentBytes = enc.GetBytes (msg); wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ()); wr.SendResponseFromMemory (contentBytes, contentBytes.Length); wr.FlushResponse (true); wr.CloseConnection (); HttpApplication.requests_total_counter.Increment (); }
void Application_Error() { ResetContext(); ServiceFactory EventLogFactory = new ServiceFactory(); Exception exception = Server.GetLastError(); if (exception != null) { Response.Clear(); HttpException httpException = new HttpException(exception.Message, exception); var cxt = new HttpContextWrapper(Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Home"); string ModuleNam ="/"+ Context.Request.RequestContext.RouteData.Values["controller"].ToString()+"/"; string FunctionName = Context.Request.RequestContext.RouteData.Values["action"].ToString(); string ExceptionalType = exception.Message; string ExceptionalDescription = exception.ToString(); string State = "1"; if (httpException != null) { switch (httpException.GetHttpCode()) { case 404: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "PageNotFound"); routeData.Values.Add("PageNotFoundLog", exception.Message); } else { routeData.Values.Add("action", "AjaxPageNotFound"); routeData.Values.Add("AjaxPageNotFoundLog", exception.Message); } break; case 500: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "ServerError"); routeData.Values.Add("ServerErrorLog", exception.Message); } else { routeData.Values.Add("action", "AjaxServerError"); routeData.Values.Add("AjaxServerErrorLog", exception.Message); } Trace.TraceError("Server Error occured and caught in Global.asax - {0}", exception.ToString()); break; default: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "Error"); routeData.Values.Add("ErrorLog", exception.Message); routeData.Values.Add("errorCode", httpException.GetHttpCode()); } else { routeData.Values.Add("action", "AjaxError"); routeData.Values.Add("AjaxErrorLog", exception.Message); routeData.Values.Add("errorCode", httpException.GetHttpCode()); } Trace.TraceError("Error occured and caught in Global.asax - {0}", exception.ToString()); break; } } EventLogFactory.GetService<IExceptionalLogService>().CreateExceptionLog(ModuleNam, FunctionName, ExceptionalType, ExceptionalDescription, State); Server.ClearError(); Response.TrySkipIisCustomErrors = true; IController errorController = new HomeController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } }