Best way to check for inner exception?

后端 未结 14 2348
说谎
说谎 2020-12-02 11:57

I know sometimes innerException is null

So the following might fail:

 repEvent.InnerException = ex.InnerException.Message; 

Is ther

14条回答
  •  广开言路
    2020-12-02 12:28

    Great answers so far. On a similar, but different note, sometimes there is more than one level of nested exceptions. If you want to get the root exception that was originally thrown, no matter how deep, you might try this:

    public static class ExceptionExtensions
    {
        public static Exception GetOriginalException(this Exception ex)
        {
            if (ex.InnerException == null) return ex;
    
            return ex.InnerException.GetOriginalException();
        }
    }
    

    And in use:

    repEvent.InnerException = ex.GetOriginalException();
    

提交回复
热议问题