PageRenderTime 49ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Sitereactor.CloudProviders/Extensions/ExceptionExtensions.cs

https://github.com/Jeavon/Cloud-Proivders-for-Universal-Media-Picker
C# | 79 lines | 55 code | 7 blank | 17 comment | 8 complexity | 218ec10408c5e6054e7fdad76e2dcbd1 MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Linq;
  4. using System.Xml.Linq;
  5. using System.Xml.XPath;
  6. namespace Sitereactor.CloudProviders.Extensions
  7. {
  8. /// <summary>
  9. /// Extension methods for exceptions.
  10. /// </summary>
  11. /// <remarks>These Exception extension methods are primarily used for the XsltExtensions methods.</remarks>
  12. public static class ExceptionExtensions
  13. {
  14. /// <summary>
  15. /// Returns the Exception message as XML.
  16. /// </summary>
  17. /// <param name="ex">The Exception object.</param>
  18. /// <returns>An XDocument of the Exception object.</returns>
  19. public static XDocument ToXml(this Exception exception)
  20. {
  21. // The root element is the Exception's type
  22. XElement root = new XElement(exception.GetType().ToString());
  23. if (exception.Message != null)
  24. {
  25. root.Add(new XElement("Message", exception.Message));
  26. }
  27. if (exception.StackTrace != null)
  28. {
  29. root.Add
  30. (
  31. new XElement("StackTrace",
  32. from frame in exception.StackTrace.Split('\n')
  33. let prettierFrame = frame.Substring(6).Trim()
  34. select new XElement("Frame", prettierFrame))
  35. );
  36. }
  37. // Data is never null; it's empty if there is no data
  38. if (exception.Data.Count > 0)
  39. {
  40. root.Add
  41. (
  42. new XElement("Data",
  43. from entry in
  44. exception.Data.Cast<DictionaryEntry>()
  45. let key = entry.Key.ToString()
  46. let value = (entry.Value == null) ?
  47. "null" : entry.Value.ToString()
  48. select new XElement(key, value))
  49. );
  50. }
  51. // Add the InnerException if it exists
  52. if (exception.InnerException != null)
  53. {
  54. root.Add
  55. (
  56. exception.InnerException.ToXml()
  57. );
  58. }
  59. return root.Document;
  60. }
  61. /// <summary>
  62. /// Returns the Exception message as a XPathNodeIterator object.
  63. /// </summary>
  64. /// <param name="ex">The Exception object.</param>
  65. /// <returns>An XPathNodeIterator instance of the Exception object.</returns>
  66. public static XPathNodeIterator ToXPathNodeIterator(this Exception exception)
  67. {
  68. XDocument doc = exception.ToXml();
  69. return doc.CreateNavigator().Select("/error");
  70. }
  71. }
  72. }