private static string ToStringAdvanced(this System.Exception exception, string exceptionFormat, string propertyFormat, IEnumerable <string> propertyFilter, string indentationString, int depth) { if (exception == null) { return(null); } exceptionFormat = exceptionFormat ?? Environment.NewLine + "{0}:" + Environment.NewLine + "{1}"; propertyFormat = propertyFormat ?? "{0} = {1}" + Environment.NewLine; propertyFilter = propertyFilter ?? new string[] { "Message", "StackTrace", "Source", "TargetSite", "InnerException" }; var properties = exception.GetType().GetProperties().Select(p => new KeyValuePair <string, string>(p.Name, Convert.ToString(p.GetValue(exception)))).ToDictionary(p => p.Key, p => p.Value); var filteredProperties = properties.Where(p => propertyFilter.Contains(p.Key) && !string.IsNullOrEmpty(p.Value)).ToDictionary(p => p.Key, p => p.Value); if (filteredProperties.ContainsKey("InnerException")) { filteredProperties["InnerException"] = exception.InnerException.ToStringAdvanced(exceptionFormat, propertyFormat, propertyFilter, indentationString, depth + 1); } var formatedProperties = filteredProperties.Select(p => string.Format(propertyFormat, p.Key, p.Value)).ToList(); var detailString = string.Format(exceptionFormat, exception.GetType().FullName, string.Join("", formatedProperties)); if (!string.IsNullOrEmpty(indentationString) && depth > 0) { string indentation = string.Concat(Enumerable.Repeat(indentationString, depth)); var lines = detailString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); detailString = Environment.NewLine + string.Join(Environment.NewLine, lines.Select(l => indentation + l)); } return(detailString); }
/// ------------------------------------------------------------------- /// <summary> /// Report that the test had an error /// </summary> /// ------------------------------------------------------------------- public static void LogError(Exception exception) { // Our test framework calls using Invoke, and throw is returned if (exception is TargetInvocationException) exception = exception.InnerException; // If a test catches the exception, and then rethrows the excpeption later, it uses "RETHROW" // to allow this global exception handler to peel this rethrow and analyze the actual exception. if (exception.Message == "RETHROW") exception = exception.InnerException; if (exception.GetType() == typeof(InternalHelper.Tests.KnownProductIssueException)) { _knownIssues++; _currentLogger.Log(new ExceptionInfo(exception, false, true, false)); LogPass(); } else if (exception.GetType() == typeof(InternalHelper.Tests.IncorrectElementConfigurationForTestException)) { _incorrectConfigurations++; _currentLogger.Log(new CommentInfo(exception.Message)); LogPass(); } else if (exception.GetType() == typeof(InternalHelper.Tests.TestErrorException)) { _currentLogger.Log(new ExceptionInfo(exception)); _currentLogger.Log(new TestResultInfo(TestResultInfo.TestResults.Failed)); } else { LogUnexpectedError(exception); } }
private string FindWarning( System.Exception ex, System.Xml.XmlDocument xmlHints) { System.Xml.XmlNodeList nodeList; string fullName; string shortName; System.Exception thisEx = ex; string sRet = ""; // Expecting only a few so no stringbuilder while (thisEx != null) { fullName = thisEx.GetType().FullName; shortName = thisEx.GetType().Name; nodeList = xmlHints.SelectNodes("//Hint[@FullName=//" + fullName + "// or @ShortName=//" + shortName + "//]/HintMessage"); foreach (System.Xml.XmlNode node in nodeList) { sRet += node.InnerText + Microsoft.VisualBasic.ControlChars.CrLf; } thisEx = thisEx.InnerException; } return(sRet); }
public void Log(Exception ex) { string path = @"Errors.txt"; if(File.Exists(path)) { using (StreamWriter log = File.AppendText(path)) { log.WriteLine("Error logged:"); log.WriteLine(ex.GetType()); log.WriteLine(ex.Message); log.WriteLine(ex.StackTrace); log.WriteLine(); } } else { using (StreamWriter log = File.CreateText(path)) { log.WriteLine(ex.GetType()); log.WriteLine(ex.StackTrace); log.WriteLine(); } } }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { JObject json = new JObject(); json.Add(JsonRpcConstants.ResultKey, null); JsonRpcException jsonException = error as JsonRpcException; if (jsonException != null) { json.Add(JsonRpcConstants.ErrorKey, jsonException.JsonException); } else { JObject exceptionJson = new JObject { { "type", error.GetType().FullName }, { "message", error.Message }, }; JObject temp = exceptionJson; while (error.InnerException != null) { error = error.InnerException; JObject innerJson = new JObject { { "type", error.GetType().FullName }, { "message", error.Message }, }; temp["inner"] = innerJson; temp = innerJson; } json.Add(JsonRpcConstants.ErrorKey, exceptionJson); } fault = JsonRpcHelpers.SerializeMessage(json, fault); }
public CommandResult HandleException(Exception ex) { if (_handlerConfigurationCollection.ContainsValueForType(ex.GetType())) return _handlerConfigurationCollection.GetForType(ex.GetType())(ex); return _handlerConfigurationCollection.GetForType(typeof(Exception))(ex); }
public string Translate(Exception e) { //TODO (CR April 2011): Figure out how to share the Exception Policies for these messages ... //Current ExceptionHandler/Policy design just doesn't work for this at all. if (e.GetType().Equals(typeof(InUseLoadStudyException))) return ImageViewer.SR.MessageLoadStudyFailedInUse; if (e.GetType().Equals(typeof(NearlineLoadStudyException))) { return ((NearlineLoadStudyException)e).IsStudyBeingRestored ? ImageViewer.SR.MessageLoadStudyFailedNearline : ImageViewer.SR.MessageLoadStudyFailedNearlineNoRestore; } if (e.GetType().Equals(typeof(OfflineLoadStudyException))) return ImageViewer.SR.MessageLoadStudyFailedOffline; if (e.GetType().Equals(typeof(NotFoundLoadStudyException))) return ImageViewer.SR.MessageLoadStudyFailedNotFound; if (e.GetType().Equals(typeof(LoadStudyException))) return SR.MessageStudyCouldNotBeLoaded; if (e is LoadMultipleStudiesException) return ((LoadMultipleStudiesException)e).GetUserMessage(); if (e.GetType().Equals(typeof(NoVisibleDisplaySetsException))) return ImageViewer.SR.MessageNoVisibleDisplaySets; if (e.GetType().Equals(typeof(PatientStudiesNotFoundException))) return SR.MessagePatientStudiesNotFound; if (e.GetType().Equals(typeof(AccessionStudiesNotFoundException))) return SR.MessageAccessionStudiesNotFound; if (e.GetType().Equals(typeof(InvalidRequestException))) return e.Message; if (e.GetType().Equals(typeof(PermissionDeniedException))) return e.Message; return null; }
protected StringBuilder getErrorInfo( HttpApplication app ) { Exception exLast = app.Server.GetLastError(); ex = exLast.GetBaseException(); ex = wrapStaticFileException( ex ); HttpRequest req = getRequest( app ); if (req == null) { StringBuilder sb = new StringBuilder(); sb.AppendLine( "ex.Message=" + ex.Message ); sb.AppendLine( "ex.Type=" + ex.GetType().FullName ); sb.AppendLine( "ex.Version=" + MvcConfig.Instance.Version ); sb.AppendLine( "ex.Source=" + getExSource( ex ) ); sb.AppendLine( "ex.StackTrace=" + getExStackTrace( ex, exLast ) ); return sb; } else { StringBuilder sb = new StringBuilder(); sb.AppendLine( "url=" + req.Url.ToString() ); sb.AppendLine( "ex.Message=" + ex.Message ); sb.AppendLine( "ex.Type="+ ex.GetType().FullName ); sb.AppendLine( "ex.Version=" + MvcConfig.Instance.Version ); appendPostValues( "ex.PostedValue=", req.Form, sb ); sb.AppendLine( "ex.Source=" + getExSource( ex ) ); sb.AppendLine( "ex.StackTrace=" + getExStackTrace( ex, exLast ) ); return sb; } }
void buildTreeLayer(System.Exception e, TreeViewItem parent) { String exceptionInformation = "\n\r\n\r" + e.GetType().ToString() + "\n\r\n\r"; parent.DisplayMemberPath = "Header"; parent.Items.Add(new TreeViewStringSet() { Header = "Type", Content = e.GetType().ToString() }); PropertyInfo[] memberList = e.GetType().GetProperties(); foreach (PropertyInfo info in memberList) { var value = info.GetValue(e, null); if (value != null) { if (info.Name == "InnerException") { TreeViewItem treeViewItem = new TreeViewItem(); treeViewItem.Header = info.Name; buildTreeLayer(e.InnerException, treeViewItem); parent.Items.Add(treeViewItem); } else { TreeViewStringSet treeViewStringSet = new TreeViewStringSet() { Header = info.Name, Content = value.ToString() }; parent.Items.Add(treeViewStringSet); exceptionInformation += treeViewStringSet.Header + "\n\r\n\r" + treeViewStringSet.Content + "\n\r\n\r"; } } } _exceptionInformationList.Add(exceptionInformation); }
public static Exception Unwrap(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (exception.InnerException == null) { return exception; } // Always return the inner exception from a target invocation exception if (exception.GetType() == typeof (TargetInvocationException)) { return exception.InnerException; } // Flatten the aggregate before getting the inner exception if (exception.GetType() == typeof (AggregateException)) { return ((AggregateException) exception).Flatten().InnerException; } return exception; }
public void Escribir_Log(System.Exception ex, string mensajeError) { string errorPrint = DateTime.Now.ToString("T") + " --> Error: "; if (ex.GetType().Name.Equals("SqlException")) { SqlException x = (SqlException)ex; errorPrint += "SqlException: " + x.Server + " Procedure " + x.Procedure + " State = " + x.State.ToString() + " Line Number = " + x.LineNumber + " Message = " + x.Message; } else if (ex.GetType().Name.Equals("FileNotFoundException")) { FileNotFoundException x = (FileNotFoundException)ex; errorPrint += "FileNotFoundException: File Name = " + x.FileName + " Message = " + x.Message; } else { errorPrint += "Mensaje: " + ex.Message; } if (string.IsNullOrEmpty(mensajeError)) { errorPrint += mensajeError; } using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(archivo), FileMode.Append, FileAccess.Write)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(errorPrint); sw.WriteLine("____________________________________________________"); } }
private System.Windows.Forms.TreeNode Exception2TreeNode(string name, System.Exception e) { if (name == null || name == "") { name = e.GetType().ToString(); } else { name += ":\t" + e.GetType().ToString(); } System.Windows.Forms.TreeNode tn = new TreeNode(name); tn.Nodes.Add("Message:" + e.Message); tn.Nodes.Add("HelpLink:\t" + e.HelpLink); tn.Nodes.Add("Source:\t" + e.Source); tn.Nodes.Add(this.StackTrace2TreeNode(e.StackTrace)); tn.Nodes.Add("TargetSite:\t" + e.TargetSite); System.Exception e2 = e.InnerException; if (e2 != null) { tn.Nodes.Add(this.Exception2TreeNode("InnerException", e2)); } e2 = e.GetBaseException(); if (e2 != null && e != e2) { tn.Nodes.Add(this.Exception2TreeNode("BaseException", e2)); } return(tn); }
public static void showException(Exception ex, string dialogTitle, string messageText = "") { if (messageText == "") { MessageBox.Show( string.Format( "{0}\n" + "\n" + "{1}", ex.GetType().ToString(), ex.Message ), "Dirigent - " + dialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show( string.Format( "{0}\n" + "\n" + "Exception: [{1}]\n" + "{2}", messageText, ex.GetType().ToString(), ex.Message ), "Dirigent - " + dialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public ActionResult UnhandledException(Exception exception) { if (exception == null) { return UnknownError(); } if (exception.GetType().Equals(typeof(HttpException))) { HttpException httpException = (HttpException)exception; Response.StatusCode = httpException.GetHttpCode(); switch (httpException.GetHttpCode()) { case 403: return Http403(httpException); case 404: return Http404(httpException); } } if (exception.GetType().Equals(typeof(EntityCommandExecutionException))) { //TODO: smartly handle database errors. } return View(exception); }
/// <summary> /// Valida, baseado na exceção disparada, se corresponde a uma exceção de timeout, que pode corresponder a diferentes tipos de exceção. /// </summary> /// <param name="exception"></param> /// <returns></returns> public static bool IsTimeoutException(this System.Exception exception) { if (exception.GetType() == typeof(AggregateException)) { AggregateException aggregateException = (AggregateException)exception; if (aggregateException.InnerExceptions.Any(e => e.GetType() == typeof(TaskCanceledException))) { return(true); } } if (exception.GetType() == typeof(TimeoutException)) { return(true); } if (exception.GetType() == typeof(System.Net.WebException)) { System.Net.WebException webException = (System.Net.WebException)exception; if (webException.Status == System.Net.WebExceptionStatus.Timeout) { return(true); } } return(false); }
public static void log(string level, string comp, string msg, Exception e) { if (comp == null) comp = ""; if (msg == null) msg = ""; var nowms = DateTimeMs.NowMs; var ts = nowms.ToShortDateString().PadLeft(10) + " " + nowms.ToLongTimeString().PadLeft(8) + "." + nowms.Millisecond.ToString().PadLeft(3, '0'); msg = "["+level+"] "+ ts + "["+comp+"] " + msg; if (e != null) { msg += "\n" + e.GetType().ToString() + ": " + e.Message +"\n"+ e.StackTrace; } if (e != null && e.GetBaseException() != null && e.GetBaseException() != e) { e = e.GetBaseException(); msg += "BaseException:\n" + e.GetType().ToString() + ": " + e.Message +"\n"+ e.StackTrace; } try{ System.Console.WriteLine(msg); #if __ANDROID__ Android.Util.Log.Error("", msg); #endif if (fs != null) { fs.Write(msg+"\n"); fs.Flush(); } }catch(Exception){} }
/// <summary> /// Record an application exception, along with a message. /// </summary> /// <param name="message">The message to record along with the exception.</param> /// <param name="exception">The exception to record.</param> public static void LogError(string message, System.Exception exception) { #if __IOS__ NativeFlurry.LogError( string.Format(exception.GetType().FullName, message), exception.ToString(), new NSException(exception.GetType().FullName, exception.Message, null)); #elif __ANDROID__ Java.Lang.Exception javaEx = new Java.Lang.Exception(exception.Message); StackTrace stackTrace = new StackTrace(exception, true); StackTraceElement[] trace = new StackTraceElement[stackTrace.FrameCount]; for (int index = 0; index < stackTrace.FrameCount; ++index) { StackFrame frame = stackTrace.GetFrame(index); trace[index] = new StackTraceElement(frame.GetMethod().DeclaringType.Name, frame.GetMethod().Name, frame.GetFileName(), frame.GetFileLineNumber()); } javaEx.SetStackTrace(trace); NativeFlurry.OnError( string.Format(exception.GetType().FullName, message), exception.ToString(), javaEx); #elif WINDOWS_PHONE NativeFlurry.LogError(message, exception); #endif }
void buildTreeLayer(Exception e, TreeViewItem parent) { String exceptionInformation = "\n\r\n\r" + e.GetType().ToString() + "\n\r\n\r"; parent.DisplayMemberPath = "Header"; parent.Items.Add(new TreeViewStringSet() { Header = "Type", Content = e.GetType().ToString() }); System.Reflection.PropertyInfo[] memberList = e.GetType().GetProperties(); foreach (PropertyInfo info in memberList) { var value = info.GetValue(e, null); if (value != null) { if (info.Name == "InnerException") { TreeViewItem treeViewItem = new TreeViewItem(); treeViewItem.Header = info.Name; buildTreeLayer(e.InnerException, treeViewItem); parent.Items.Add(treeViewItem); } else { TreeViewStringSet treeViewStringSet = new TreeViewStringSet() { Header = info.Name, Content = value.ToString() }; parent.Items.Add(treeViewStringSet); exceptionInformation += treeViewStringSet.Header + "\n\r\n\r" + treeViewStringSet.Content + "\n\r\n\r"; } } } ExceptionInformationList.Add(exceptionInformation); }
public ErrorReport(string s, Exception ex) { InitializeComponent(); var message = new StringBuilder(); message.AppendLine("MTMCL, version " + MeCore.version); message.AppendLine(s); message.AppendLine("\n\n-----------------ERROR REPORT----------------------\n"); message.AppendFormat("Target Site: {0}", ex.TargetSite).AppendLine(); message.AppendFormat("Error Type: {0}", ex.GetType()).AppendLine(); message.AppendFormat("Messge: {0}", ex.Message).AppendLine(); foreach (DictionaryEntry data in ex.Data) message.AppendLine(string.Format("Key:{0}\nValue:{1}", data.Key, data.Value)); message.AppendLine(ex.StackTrace); var iex = ex; while (iex.InnerException != null) { message.AppendLine("------------Inner Exception------------"); iex = iex.InnerException; message.AppendFormat("Target Site: {0}", ex.TargetSite).AppendLine(); message.AppendFormat("Error Type: {0}", ex.GetType()).AppendLine(); message.AppendFormat("Messge: {0}", ex.Message).AppendLine(); foreach (DictionaryEntry data in ex.Data) message.AppendLine(string.Format("Key:{0}\nValue:{1}", data.Key, data.Value)); message.AppendLine("StackTrace"); message.AppendLine(iex.StackTrace); } CreateLogInfoPart(message); txtMes.Text = message.ToString(); }
private static void WriteErrorToFile(Configuration config, System.Exception e) { string path = Path.Combine(config.Output, "TestRunnerLogs"); string filePath = Path.Combine(path, "TestRunner_Errors.txt"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } StringBuilder errorLogEntry = new StringBuilder(); errorLogEntry.AppendFormat("DATE/TIME : {0} - {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToLongTimeString()); errorLogEntry.AppendLine(); errorLogEntry.AppendFormat("EXCEPTION : {0}.{1}", e.GetType().Namespace, e.GetType().Name); errorLogEntry.AppendLine(); errorLogEntry.AppendFormat("MESSAGE : {0}", e.Message); errorLogEntry.AppendLine(); errorLogEntry.AppendFormat("TRACE {0}{1}", System.Environment.NewLine, e.StackTrace); errorLogEntry.AppendLine(); if (e.InnerException != null) { errorLogEntry.AppendFormat("INNEREXCEPTION : {0}.{1}", e.InnerException.GetType().Namespace, e.InnerException.GetType().Name); errorLogEntry.AppendLine(); errorLogEntry.AppendFormat("INNER MESSAGE : {0}", e.InnerException.Message); errorLogEntry.AppendLine(); } errorLogEntry.AppendLine(); errorLogEntry.AppendLine("****************************************************************************************************************************"); errorLogEntry.AppendLine(); File.AppendAllText(filePath, errorLogEntry.ToString()); }
/// <summary> /// Convert an exception thrown by an RPC into an error message. /// </summary> internal static Error HandleException(System.Exception exn) { if (exn is RPCException && exn.InnerException != null) { exn = exn.InnerException; } var message = exn.Message; var verboseErrors = Configuration.Instance.VerboseErrors; var stackTrace = verboseErrors ? exn.StackTrace : string.Empty; if (Logger.ShouldLog(Logger.Severity.Debug)) { Logger.WriteLine(message, Logger.Severity.Debug); if (verboseErrors) { Logger.WriteLine(stackTrace, Logger.Severity.Debug); } } var mappedType = Service.Services.Instance.GetMappedExceptionType(exn.GetType()); var type = mappedType ?? exn.GetType(); Error error; if (Reflection.HasAttribute <KRPCExceptionAttribute>(type)) { error = new Error(TypeUtils.GetExceptionServiceName(type), type.Name, message, stackTrace); } else { error = new Error(message, stackTrace); } return(error); }
private static void WriteException(System.Exception ex) { string title = "*** Error converting from Roman Numerals"; string romanNumeral = ""; if (ex.GetType() == typeof(SymbolsRepetitionException)) { title += "\nSymbol Repetion Error:"; romanNumeral = ((SymbolsRepetitionException)ex).RomanNumeral; } else if (ex.GetType() == typeof(InvalidSubtractionException)) { title += "\nInvalid Symbol Subtraction:"; romanNumeral = ((InvalidSubtractionException)ex).RomanNumeral; } else if (ex.GetType() == typeof(SymbolValidationException)) { title += "\nSymbol Validation Error:"; romanNumeral = ((SymbolValidationException)ex).RomanNumeral; } else { title = "*** Unexpected Error"; } var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine(); System.Console.WriteLine(title); System.Console.WriteLine(ex.Message); System.Console.WriteLine("Roman Numeral: " + romanNumeral); System.Console.WriteLine(); Console.ForegroundColor = color; }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { var errorModel = new ErrorModel {Message = error.Message, Type = error.GetType().Name, Success = false}; fault = Message.CreateMessage(version, null, errorModel, new DataContractJsonSerializer(typeof (ErrorModel))); fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json)); if (IsAuthenticationException(error)) { var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.Unauthorized}; rmp.StatusDescription = rmp.StatusCode.ToString(); rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; fault.Properties.Add(HttpResponseMessageProperty.Name, rmp); } else if (error.GetType() == typeof (InvalidOperationException) || error.GetType() == typeof (ArgumentException)) { var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.BadRequest}; rmp.StatusDescription = rmp.StatusCode.ToString(); rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; fault.Properties.Add(HttpResponseMessageProperty.Name, rmp); } else { errorModel.Message = "Unable to perform the operation"; var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.InternalServerError}; rmp.StatusDescription = rmp.StatusCode.ToString(); rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; fault.Properties.Add(HttpResponseMessageProperty.Name, rmp); } }
private async Task HandleExceptionAsync(HttpContext httpContext, System.Exception e) { httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var message = ExceptionMessage.InternalServerError; if (e.GetType() == typeof(ValidationException)) { message = e.Message; } if (e.GetType() == typeof(ApplicationException)) { message = e.Message; } if (e.GetType() == typeof(UnauthorizedAccessException)) { message = e.Message; httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; } // _logger.Error(e.ToString()); await httpContext.Response.WriteAsync(new ErrorDetails { StatusCode = httpContext.Response.StatusCode, Message = message }.ToString()); }
/// <summary> /// INTERNAL /// </summary> /// <param name="error">The exception to format.</param> public static string FormatException(Exception error) { if (error == null) throw new ArgumentNullException("error"); //?? _090901_055134 Regex is used to fix bad PS V1 strings; check V2 Regex re = new Regex("[\r\n]+"); string info = error.GetType().Name + ":" + Environment.NewLine + re.Replace(error.Message, Environment.NewLine) + Environment.NewLine; // get an error record if (error.GetType().FullName.StartsWith("System.Management.Automation.", StringComparison.Ordinal)) { object errorRecord = GetPropertyValue(error, "ErrorRecord"); if (errorRecord != null) { // process the error record object ii = GetPropertyValue(errorRecord, "InvocationInfo"); if (ii != null) { object pm = GetPropertyValue(ii, "PositionMessage"); if (pm != null) //?? 090517 Added Trim(), because a position message starts with an empty line info += re.Replace(pm.ToString().Trim(), Environment.NewLine) + Environment.NewLine; } } } if (error.InnerException != null) info += Environment.NewLine + FormatException(error.InnerException); return info; }
/// <summary> /// Displays exception information. Should be called from try...catch handlers /// </summary> /// <param name="ex">Exception object to handle</param> new public static void Handle(Exception ex) { if (ex != null) { if (ex is System.Net.WebException) { MessageBox.Show(ex.Message, "Network access error. Please try again later", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ErrorHandler handler = new ErrorHandler(); handler.txtError.Text = ex.Message; handler.txtDetails.Text = "{{AWB bug\r\n | status = new <!-- when fixed replace with \"fixed\" -->\r\n | description = Exception: " + ex.GetType().Name + "\r\nMessage: " + ex.Message + "\r\nCall stack:" + ex.StackTrace + "\r\n~~~~\r\n | OS = " + Environment.OSVersion.ToString() + "\r\n | version = " + Assembly.GetExecutingAssembly().GetName().Version.ToString(); handler.txtDetails.Text += "\r\n}}"; handler.textBox1.Text = "AWB Updater encountered " + ex.GetType().Name; handler.ShowDialog(); } } }
public static void Fatal(Exception ex, string Source) { HttpContext.Current.Response.StatusCode = 500; try { try { if (ex.GetBaseException().GetType().ToString() == "MySql.Data.MySqlClient.MySqlException") MySqlConnection.ClearAllPools(); } catch { } Fatal("[" + ex.GetBaseException().GetType().ToString() + "]" + ex.GetBaseException().Message, ex.GetBaseException().ToString(), "Fatal " + ex.GetBaseException().GetType().ToString(), Source); } catch { try { if (ex.GetType().ToString() == "MySql.Data.MySqlClient.MySqlException") MySqlConnection.ClearAllPools(); } catch { } Fatal("[" + ex.GetType().ToString() + "]" + ex.Message, ex.ToString(), "Fatal " + ex.GetType().ToString(), Source); } }
protected virtual bool ExceptionImpl(System.Exception ex) { lock (this) { _ex = ex; if (ChildObserver != null) { ChildObserver.Failed(ex.GetType().FullName); ChildObserver.Detach(); ChildObserver = null; } _cancellationHandler = null; if (Observer != null) { Observer.Failed(ex.GetType().FullName); } bool invoke = _completionCallback.HandleException(ex, this); if (!invoke && Observer != null) { Observer.Detach(); Observer = null; } return(invoke); } }
public void Error( System.Exception exception) { Sample.Current.Error( _actorId, _processId, _machineName, exception ); System.Diagnostics.Debug.WriteLine($"[Console, Error] ERR: Error"); System.Diagnostics.Debug.WriteLine($"\t_actorId.ToString():\t{_actorId.ToString()}"); System.Diagnostics.Debug.WriteLine($"\t_actorId.Kind.ToString():\t{_actorId.Kind.ToString()}"); System.Diagnostics.Debug.WriteLine($"\t_processId:\t{_processId}"); System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}"); System.Diagnostics.Debug.WriteLine($"\texception.Message:\t{exception.Message}"); System.Diagnostics.Debug.WriteLine($"\texception.Source:\t{exception.Source}"); System.Diagnostics.Debug.WriteLine($"\texception.GetType().FullName:\t{exception.GetType().FullName}"); System.Diagnostics.Debug.WriteLine($"\texception.AsJson():\t{exception.AsJson()}"); _telemetryClient.TrackException( exception, new System.Collections.Generic.Dictionary <string, string>() { { "Name", "Error" }, { "ActorId", _actorId.ToString() }, { "ActorIdType", _actorId.Kind.ToString() }, { "ProcessId", _processId.ToString() }, { "MachineName", Environment.MachineName }, { "Message", exception.Message }, { "Source", exception.Source }, { "ExceptionTypeName", exception.GetType().FullName }, { "Exception", exception.AsJson() } }); }
public void UnsupportedKeyError( System.Exception ex) { FGDiagnosticsAutoLoggerSamplesConsoleApplication1EventSource.Current.UnsupportedKeyError( _autogenerated, _machineName, ex ); System.Diagnostics.Debug.WriteLine($"[ConsoleRunner, Error] ERR: UnsupportedKeyError"); System.Diagnostics.Debug.WriteLine($"\t_autogenerated:\t{_autogenerated}"); System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}"); System.Diagnostics.Debug.WriteLine($"\tex.Message:\t{ex.Message}"); System.Diagnostics.Debug.WriteLine($"\tex.Source:\t{ex.Source}"); System.Diagnostics.Debug.WriteLine($"\tex.GetType().FullName:\t{ex.GetType().FullName}"); System.Diagnostics.Debug.WriteLine($"\tex.AsJson():\t{ex.AsJson()}"); _telemetryClient.TrackException( ex, new System.Collections.Generic.Dictionary <string, string>() { { "Name", "UnsupportedKeyError" }, { "Autogenerated", _autogenerated.ToString() }, { "MachineName", Environment.MachineName }, { "Message", ex.Message }, { "Source", ex.Source }, { "ExceptionTypeName", ex.GetType().FullName }, { "Exception", ex.AsJson() } }); }
public void SetError(Exception exception) { HasError = true; ExceptionType = exception.GetType(); if (ExceptionType == typeof(AggregateException)) { exception = GetInitialException(exception); ExceptionType = exception.GetType(); } foreach (var stackTrace in _stackTraceList.AsEnumerable().Reverse()) { StackTrace += stackTrace + "\n"; } if (ExceptionType == typeof(HttpRequestException)) { ExceptionTitle = "Error fetching data"; ExceptionOriginalMessage = exception.Message; ExceptionMessage = exception.Message + " Please check your connection and try again, cached data will still show up in the app."; } else { ExceptionTitle = "Unhandleded error occured"; ExceptionOriginalMessage = exception.Message; ExceptionMessage = exception.Message; } }
public static bool IsFatal(Exception exception) { while (exception != null) { if (exception.GetType().Name == "FatalException" || (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || exception is ThreadAbortException || exception.GetType().Name == "FatalInternalException") { return true; } // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions, // we want to check to see whether they've been used to wrap a fatal exception. If so, then they // count as fatal. if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; } else { break; } } return false; }
protected virtual Message GetJsonFaultMessage(MessageVersion version, Exception error) { BaseFault detail = null; var knownTypes = new List<Type>(); string faultType = error.GetType().Name; //default if ((error is FaultException) && (error.GetType().GetProperty("Detail") != null)) { detail = (error.GetType().GetProperty("Detail").GetGetMethod().Invoke( error, null) as BaseFault); knownTypes.Add(detail.GetType()); faultType = detail.GetType().Name; } var jsonFault = new JsonFault { Message = error.Message, Detail = detail, FaultType = faultType }; var faultMessage = Message.CreateMessage(version, "", jsonFault, new DataContractJsonSerializer(jsonFault.GetType(), knownTypes)); return faultMessage; }
/// <summary> /// Handles logging for workflow exception /// </summary> public static void HandleWorkflowException(Exception ex) { if (ex.GetType() != typeof(WorkflowException) || ex.GetType().BaseType != typeof(WorkflowException)) { HandleException(ex); } ExceptionPolicy.HandleException(ex, EnterpriseLibraryResources.ExceptionPolicy_Workflow); }
public ExceptionResult(Exception exception) : this(exception.GetType().FullName, exception.GetType().Name, exception.Message, exception.StackTrace, null) { if (exception.InnerException != null) { InnerExceptionResult = new ExceptionResult(exception.InnerException); } }
public ExceptionResult(Exception exception) { FullTypeName = exception.GetType().FullName; TypeName = exception.GetType().Name; Message = exception.Message; _toString = exception.ToString(); StackTrace = exception.StackTrace; }
public HoptoadError ErrorFromException(Exception exception) { var error = new HoptoadError { Class = exception.GetType().FullName, Message = exception.GetType().Name + ": " + exception.Message, Backtrace = this.BuildBacktrace(exception).ToArray(), }; return error; }
public ServiceFault(Exception ex) { this.Exception = ex.GetType().Name; this.Type = ex.GetType().FullName; this.Message = ex.Message; this.StackTrace = ex.StackTrace; this.InnerException = ex.InnerException; }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionInfo"/> class from an <see cref="Exception"/>. /// </summary> /// <param name="exception">The exception used to initialize the properties of this instance.</param> public ExceptionInfo(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Message = exception.Message; StackTrace = exception.StackTrace; TypeFullName = exception.GetType().FullName; TypeName = exception.GetType().Name; InnerException = exception.InnerException != null ? new ExceptionInfo(exception.InnerException) : null; }
public static void W(Exception ex) { writeLog( "*W WARNING\t" + ex.Message, ex.GetType().Name, "(" + ex.GetType().FullName + ")", ex.StackTrace ); Reported(new LogMessageInfo(LogMessageType.Warning, ex)); }
private static void ReflectException(Exception ex, int lvl, ref StringBuilder stringBuilder) { string pad = ""; for (int i = 0; i < lvl; i++) pad += paddingString; stringBuilder.AppendLine("Exception type: " + ex.GetType().Name); //stringBuilder.AppendLine(pad + ex.Message);) foreach (var field in ex.GetType().GetProperties()) { if (field.Name != "InnerException") { object val = field.GetValue(ex, null); if (val != null) { string fVal = val.ToString(); if (!string.IsNullOrEmpty(fVal) && fVal == " ") { var ienum = val as IEnumerable; Type valType = val.GetType(); if (ienum != null && !valType.IsPrimitive && valType != typeof (string)) { stringBuilder.AppendLine(pad + "[" + field.Name + "] = {"); foreach (var variable in ienum) { stringBuilder.AppendLine(pad + paddingString + "{1}" + variable); } stringBuilder.AppendLine(pad + "}"); } else { stringBuilder.AppendFormat("{2}[{0}] = \"{1}\"", field.Name, fVal, pad); stringBuilder.AppendLine(); } } else { stringBuilder.AppendFormat("{1}[{0}] = \"{2}\"", field.Name, pad, val); } } else { stringBuilder.AppendFormat("{1}[{0}] = \"{2}\"", field.Name, pad, val); } stringBuilder.AppendLine(); } } if (ex.InnerException != null) { stringBuilder.AppendLine(pad + "InnerException" + "= {"); ReflectException(ex.InnerException, lvl + 1, ref stringBuilder); stringBuilder.AppendLine(pad + "}"); } }
public static void E(Exception ex) { writeLog( "*E ERROR \t" + ex.Message, ex.GetType().Name, "(" + ex.GetType().FullName + ")", ex.StackTrace ); Flush(); Reported(new LogMessageInfo(LogMessageType.Error, ex)); }
public static void F(Exception ex) { writeLog( "*F FATAL \t" + ex.Message, ex.GetType().Name, "(" + ex.GetType().FullName + ")", ex.StackTrace ); Flush(); Reported(new LogMessageInfo(LogMessageType.Fatal, ex)); }
public ExceptionInfo(Exception ex) { this.ExceptionAssemblyName = ex.GetType ().Assembly.GetName ().FullName; this.ExceptionTypeName = ex.GetType ().FullName; this.ExceptionMessage = ex.Message; this.ExceptionStackTrace = ex.StackTrace; if (ex.InnerException != null) this.Inner = new ExceptionInfo (ex.InnerException); }
public System.Windows.Forms.DialogResult Show( System.Exception ex) { System.Windows.Forms.TreeNode nodeDeep; nodeDeep = LoadTreeNode(ex, tvExc.Nodes); tvExc.SelectedNode = nodeDeep; this.mExcFullName = ex.GetType().FullName; this.mExcShortName = ex.GetType().Name; return(this.ShowDialog()); }
internal static ModelException CreateModelException(System.Exception exception) { var modelException = new ModelException { Type = exception.GetType().ToString(), Message = exception.Message, StackTrace = exception.StackTrace }; if (exception is AggregateException aggregateException) { if (aggregateException.InnerExceptions.Count != 0) { modelException.InnerExceptions = new List <ModelException>(); foreach (var innerException in aggregateException.InnerExceptions) { modelException.InnerExceptions.Add(CreateModelException(innerException)); } } } if (exception.InnerException != null) { modelException.InnerExceptions = modelException.InnerExceptions ?? new List <ModelException>(); modelException.InnerExceptions.Add(CreateModelException(exception.InnerException)); } return(modelException); }
private static void doLogError(System.Exception e) { if (!isInitialized) { return; } StackTrace stackTrace = new StackTrace(e, true); string[] classes = new string[stackTrace.FrameCount]; string[] methods = new string[stackTrace.FrameCount]; string[] files = new string[stackTrace.FrameCount]; int[] lineNumbers = new int[stackTrace.FrameCount]; String message = ""; for (int i = 0; i < stackTrace.FrameCount; i++) { StackFrame frame = stackTrace.GetFrame(i); classes [i] = frame.GetMethod().DeclaringType.Name; methods [i] = frame.GetMethod().Name; files [i] = frame.GetFileName(); lineNumbers [i] = frame.GetFileLineNumber(); message += classes[i] + "."; message += methods[i] + "() (at "; message += files [i] + ":"; message += lineNumbers[i] + ")"; } reportException(TESTIN_CRASH_TYPE, e.GetType().Name, message); }
/// <summary> /// 创建异常消息 /// </summary> /// <param name="ex">异常信息</param> /// <param name="remark">备注</param> /// <returns>结果</returns> private static StringBuilder CreateErrorMessage(System.Exception ex, string remark) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("************************Exception Start********************************"); string newLine = Environment.NewLine; stringBuilder.Append(newLine); stringBuilder.AppendLine("Exception Remark:" + remark); System.Exception innerException = ex.InnerException; stringBuilder.AppendFormat("Exception Date:{0}{1}", DateTime.Now, Environment.NewLine); if (innerException != null) { stringBuilder.AppendFormat("Inner Exception Type:{0}{1}", innerException.GetType(), newLine); stringBuilder.AppendFormat("Inner Exception Message:{0}{1}", innerException.Message, newLine); stringBuilder.AppendFormat("Inner Exception Source:{0}{1}", innerException.Source, newLine); stringBuilder.AppendFormat("Inner Exception StackTrace:{0}{1}", innerException.StackTrace, newLine); } stringBuilder.AppendFormat("Exception Type:{0}{1}", ex.GetType(), newLine); stringBuilder.AppendFormat("Exception Message:{0}{1}", ex.Message, newLine); stringBuilder.AppendFormat("Exception Source:{0}{1}", ex.Source, newLine); stringBuilder.AppendFormat("Exception StackTrace:{0}{1}", ex.StackTrace, newLine); stringBuilder.Append("************************Exception End************************************"); stringBuilder.Append(newLine); return(stringBuilder); }
private void RunWithoutDebuggerFinalize() // On main UI thread. { IOutputStream outputStream = Solution.Current.GetMessage(false); if (null != workerParams.ExecException) { System.Exception ex = workerParams.ExecException; switch (ex.GetType().ToString()) { case "ProtoCore.Exceptions.CompileErrorsOccured": Logger.LogInfo("ExecuteFromCode-CompileErrorsOccured", ex.Message); /* * outputStream.Write(new ProtoCore.OutputMessage(OutputMessage.MessageType.Error, ex.Message)); */ break; default: Logger.LogInfo("ExecuteFromCode-CompileErrorsOccured-Ex", ex.Message); outputStream.Write(new ProtoCore.OutputMessage(OutputMessage.MessageType.Error, ex.Message)); break; } } DisplayCoreDump(workerParams.RegularRunMirror, outputStream); Logger.LogPerf("ExecuteFromCode-ms", workerParams.ElapsedMilliseconds.ToString()); string elapsed = string.Format("Time elapsed: {0} ms", workerParams.ElapsedMilliseconds); outputStream.Write(new ProtoCore.OutputMessage(OutputMessage.MessageType.Info, elapsed)); CleanUpRunners(); }
internal static void ReportException(System.Exception exc, Ice.Instrumentation.IDispatchObserver?dispatchObserver, Ice.Current current) { bool userException = exc is Ice.UserException; if (!userException && current.Adapter.Communicator.GetPropertyAsInt("Ice.Warn.Dispatch") > 0) { Warning(exc, current); } if (userException) { dispatchObserver?.UserException(); } else { if (dispatchObserver != null) { // TODO: temporary, should just use ToString all the time if (exc is Ice.Exception ex) { dispatchObserver.Failed(ex.ice_id()); } else { dispatchObserver.Failed(exc.GetType().FullName); } } } }
static string GetErrorFormatString(System.Exception ex) { if (ex == null) { return(""); } StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine("*********************异常文本*********************"); sb.AppendLine("【出现时间】:" + DateTime.Now.ToString()); sb.AppendLine("【异常类型】:" + ex.GetType().Name); sb.AppendLine("【异常信息】:" + ex.Message); sb.AppendLine("【堆栈调用】:" + ex.StackTrace); sb.AppendLine("******************************************************************"); if (ex.InnerException != null) { sb.AppendLine(GetErrorFormatString(ex.InnerException)); } return(sb.ToString()); }
/// <summary> /// Handles the error. /// </summary> /// <param name="ex">The ex.</param> /// <exception cref="Peachpie.Library.PDO.PDOException"> /// </exception> internal protected void HandleError(System.Exception ex) { // fill errorInfo Driver.HandleException(ex, out _errorSqlState, out _errorCode, out _errorMessage); // TryGetAttribute(PDO_ATTR.ATTR_ERRMODE, out var errmode); switch ((PDO_ERRMODE)errmode.ToLong()) { case PDO_ERRMODE.ERRMODE_SILENT: break; case PDO_ERRMODE.ERRMODE_WARNING: PhpException.Throw(PhpError.E_WARNING, ex.Message); break; case PDO_ERRMODE.ERRMODE_EXCEPTION: if (ex is Pchp.Library.Spl.Exception pex) { throw new PDOException(pex.Message, pex.getCode(), pex); } else { throw new PDOException(ex.GetType().Name + ": " + ex.Message); } } }
private static string StackTrace(System.Exception e) { // Allowing for the fact that the "name" and "reason" of the outermost // exception e are already shown in the Crittercism portal, we don't // need to repeat that bit of info. However, for InnerException's, we // will include this information in the StackTrace . The horizontal // lines (hyphens) separate InnerException's from each other and the // outermost Exception e . string answer = e.StackTrace; // Using seen for cycle detection to break cycling. List <System.Exception> seen = new List <System.Exception> (); seen.Add(e); if (answer != null) { // There has to be some way of telling where InnerException ie stacktrace // ends and main Exception e stacktrace begins. This is it. answer = ((e.GetType().FullName + " : " + e.Message + "\r\n") + answer); System.Exception ie = e.InnerException; while ((ie != null) && (seen.IndexOf(ie) < 0)) { seen.Add(ie); answer = ((ie.GetType().FullName + " : " + ie.Message + "\r\n") + (ie.StackTrace + "\r\n") + answer); ie = ie.InnerException; } } else { answer = ""; } return(answer); }
private Task HandleException(ref HttpContext context, ref System.Exception exception) { Devon4NetLogger.Error(exception); var exceptionTypeValue = exception.GetType(); var exceptionInterfaces = exceptionTypeValue.GetInterfaces().Select(i => i.Name).ToList(); exceptionInterfaces.Add(exceptionTypeValue.Name); return(exceptionInterfaces switch { { } exceptionType when exceptionType.Contains("InvalidDataException") => HandleContext(ref context, StatusCodes.Status422UnprocessableEntity), { } exceptionType when exceptionType.Contains("ArgumentException") || exceptionType.Contains("ArgumentNullException") || exceptionType.Contains("NotFoundException") || exceptionType.Contains("FileNotFoundException") => HandleContext(ref context, StatusCodes.Status400BadRequest), { } exceptionType when exceptionType.Contains("IWebApiException") => HandleContext(ref context, ((IWebApiException)exception).StatusCode, exception.Message, ((IWebApiException)exception).ShowMessage), _ => HandleContext(ref context, StatusCodes.Status500InternalServerError, exception.Message) });
/// <summary> /// Returns a string representation of this exception, including /// any inner exceptions. /// </summary> /// <returns>The string representation of this exception.</returns> public override string ToString() { // // This prints the exception Java style. That is, the outermost // exception, "Caused by:" to the innermost exception. The // stack trace is not nicely indented as with Java, but // without string parsing (perhaps tokenize on "\n"), it // doesn't appear to be possible to reformat it. // System.IO.StringWriter sw = new System.IO.StringWriter(CultureInfo.CurrentCulture); IceUtilInternal.OutputBase op = new IceUtilInternal.OutputBase(sw); op.setUseTab(false); op.print(GetType().FullName); op.inc(); IceInternal.ValueWriter.write(this, op); sw.Write("\n"); sw.Write(StackTrace); System.Exception curr = InnerException; while (curr != null) { sw.Write("\nCaused by: "); sw.Write(curr.GetType().FullName); if (!(curr is Ice.Exception)) { sw.Write(": "); sw.Write(curr.Message); } sw.Write("\n"); sw.Write(curr.StackTrace); curr = curr.InnerException; } return(sw.ToString()); }
public bool Add(string ModuleName, string FunctionName, System.Exception ex) { AUTH_EXCEPTIONAL_LOG ExLog = new AUTH_EXCEPTIONAL_LOG(); ExLog.EXCEPTIONAL_LOG_ID = ExceptionalLogRepository.GetNewID("AUTH_EXCEPTIONAL_LOG", "EXCEPTIONAL_LOG_ID"); ExLog.MODULE_NAME = ModuleName; ExLog.FUNCTION_NAME = FunctionName; ExLog.CATCH_TIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string ExcMsg = ""; if (ex is System.Data.Entity.Validation.DbEntityValidationException) { ExcMsg = ((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage; } else if (ex is System.Data.Entity.Validation.DbUnexpectedValidationException) { } else if (ex is System.Data.Entity.ModelConfiguration.ModelValidationException) { } else { ExcMsg = ex.Message; } ExLog.EXCEPTIONAL_TYPE = ex.GetType().ToString(); ExLog.EXCEPTIONAL_DESCRIPTION = ExcMsg; ExLog.STATE = ""; ExceptionalLogRepository.Add(ExLog); ExceptionalLogRepository.SaveChanges(); return(true); }
private Task HandleException(ref HttpContext context, ref System.Exception exception) { var exceptionTypeValue = exception.GetType(); List <string> exceptionInterfaces = exceptionTypeValue.GetInterfaces().Select(i => i.Name).ToList(); exceptionInterfaces.Add(exceptionTypeValue.Name); switch (exceptionInterfaces) { case List <string> exceptionType when exceptionType.Contains("InvalidDataException"): return(HandleContext(ref context, StatusCodes.Status422UnprocessableEntity)); case List <string> exceptionType when exceptionType.Contains("ArgumentException") || exceptionType.Contains("ArgumentNullException") || exceptionType.Contains("NotFoundException") || exceptionType.Contains("FileNotFoundException"): return(HandleContext(ref context, StatusCodes.Status400BadRequest)); case List <string> exceptionType when exceptionType.Contains("IWebApiException"): return(HandleContext(ref context, ((IWebApiException)exception).StatusCode, ((IWebApiException)exception).ShowMessage ? exception.Message : null)); default: return(HandleContext(ref context, StatusCodes.Status500InternalServerError)); } }
public static void Analyse(System.Exception ex, Boolean includeStackTrace = false) { log4net.Core.Level logLevel = log4net.Core.Level.Error; if (LoggingAsFail(ex)) { if (ex is ApplicationException) { return; } logLevel = Program.MyFailLevel; } log.ErrorOrFail(ex.GetType().FullName + ": " + ex.Message, logLevel); int errorCode = getErrorCode(ex); log.ErrorOrFail("Code: 0x" + errorCode.ToString("X8") + ";" + errorCode.ToString(), logLevel); if (ex.InnerException != null) { log.ErrorOrFail("InnerException:-", logLevel); Analyse(ex.InnerException, false); } if (includeStackTrace) { log.ErrorOrFail(ex.StackTrace, logLevel); } }
private static void doLogError(System.Exception e) { StackTrace stackTrace = new StackTrace(e, true); string[] classes = new string[stackTrace.FrameCount]; string[] methods = new string[stackTrace.FrameCount]; string[] files = new string[stackTrace.FrameCount]; int[] lineNumbers = new int[stackTrace.FrameCount]; string name = e.GetType().Name; string stack = ""; for (int i = 0; i < stackTrace.FrameCount; i++) { StackFrame frame = stackTrace.GetFrame(i); classes[i] = frame.GetMethod().DeclaringType.Name; methods[i] = frame.GetMethod().Name; files[i] = frame.GetFileName(); lineNumbers[i] = frame.GetFileLineNumber(); stack += classes[i] + "."; stack += methods[i] + "() (at "; stack += files[i] + ":"; stack += lineNumbers[i] + ")\n"; } if (lastExceptionName == "" || lastExceptionName.CompareTo(name) != 0) { lastExceptionName = name; reportException(name, stack); } }
private static void LogInternalException(string message, System.Exception e, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { var logger = GetLogger(fullClassName.FullName, methodName); var formattedOutput = new StringBuilder(); formattedOutput.AppendLine("-------------------------- Begin exception --------------------------"); formattedOutput.AppendLine(CultureInfo.InvariantCulture, $"Message: {message}"); do { formattedOutput.Append( "\n" + $"Exception full name : {e.GetType().FullName}\n" + $"Exception message : {e.Message}\n" + $"Exception stack trace:\n{e.StackTrace}\n" + $"Exception source : {e.Source}\n" + $"Exception target site: {e.TargetSite}\n" + $"Exception HResult : {e.HResult}\n"); e = e.InnerException; }while (e != null); formattedOutput.AppendLine("-------------------------- End exception --------------------------"); LogInternal(LogLevel.Error, formattedOutput.ToString(), logger, sourceFilePath, sourceLineNumber); }