Sunday, May 30, 2010

Exception formatting

public StackFrame ExtractPrimaryFrame(
  Exception exception)
{
  if (exception.InnerException != null)
  {
    return ExtractPrimaryFrame(exception.InnerException);
  }

  return ExtractPrimaryFrame(new StackTrace(exception, true));
}

public StackFrame ExtractPrimaryFrame(
  StackTrace stackTrace)
{
  if (stackTrace == null ||
    stackTrace.GetFrames() == null)
  {
    return null;
  }

  foreach (var frame in stackTrace.GetFrames())
  {
    if (frame.GetFileName() != null)
      return frame;
  }

  return null;
}

public string FormatException(Exception exception)
{
  StackFrame primaryFrame = ExtractPrimaryFrame(exception);
  return string.Format("{0} || {1}",
    FormatFrame(primaryFrame),
    exception);
}

public string FormatFrame(StackFrame frame)
{
  if (frame == null)
  {
    return string.Empty;
  }

  return string.Format(
    "FileName: {0}; Line: {1}; FilePath: {2}; Full info: {3}",
    ExtractFileName(frame.GetFileName(), "src") ?? "(none)",
    frame.GetFileLineNumber(),
    frame.GetFileName() ?? "(none)",
    frame.ToString());
}

private static string ExtractFileName(string filePath)
{
  if (string.IsNullOrEmpty(filePath))
    return null;
  FileInfo fi = new FileInfo(filePath);
  return fi.Name;
}

public string ExtractFileName(string filePath, string folderStart)
{
  if (string.IsNullOrEmpty(filePath))
    return null;
  FileInfo fi = new FileInfo(filePath);
  DirectoryInfo dir = fi.Directory;
  while (true)
  {
    if (dir.Parent == null || dir.Name == folderStart)
      break;
    dir = dir.Parent;
  }

  if (dir.Parent == null)
    return ExtractFileName(filePath);
  return fi.FullName.Replace(dir.FullName + "\\", "");
}

No comments: