andrew4582

GetRootException

Oct 27th, 2012
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1.         /// <summary>
  2.         /// Looks at all the inner exceptions of the <paramref name="exception"/> parameter to find the
  3.         /// most likely root cause of the exception. This works by skipping all registered exception types.
  4.         /// </summary>
  5.         /// <remarks>
  6.         /// This method is not 100% accurate and should only be used to point a developer into the most likely direction.
  7.         /// It should not be used to replace the Inner Exception stack of an exception, because this might hide required exception
  8.         /// information.
  9.         /// </remarks>
  10.         /// <param name="exception">The exception that will provide the list of inner exeptions to examine.</param>
  11.         /// <returns>
  12.         /// The exception that most likely caused the exception to occur. If it can't find the root exception, it will return the
  13.         /// <paramref name="exception"/> value itself.
  14.         /// </returns>
  15.         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We have to catch exception. This method is used in exception handling code, so it must not fail.")]
  16.         public static Exception GetRootException(this Exception exception)
  17.         {
  18.             Exception rootException = exception;
  19.  
  20.             try
  21.             {
  22.                 while (true)
  23.                 {
  24.                     if (rootException == null)
  25.                     {
  26.                         rootException = exception;
  27.                         break;
  28.                     }
  29.                      
  30.                     rootException = rootException.InnerException;
  31.                 }
  32.             }
  33.             catch (Exception)
  34.             {
  35.                 rootException = exception;
  36.             }
  37.             return rootException;
  38.         }
Advertisement
Add Comment
Please, Sign In to add comment