Best way to check for inner exception?

后端 未结 14 2259
说谎
说谎 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:31

    Why so much recursion in these answers?

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

    Seems like a much more straight forward way to implement this.

    0 讨论(0)
  • 2020-12-02 12:33

    Is this what you are looking for?

    String innerMessage = (ex.InnerException != null) 
                          ? ex.InnerException.Message
                          : "";
    
    0 讨论(0)
  • 2020-12-02 12:34

    With C# 6.0 you can do it in one line.

    repEvent.InnerException = ex.InnerException?.Message; 
    

    for other feature of C# 6.0 click here

    0 讨论(0)
  • 2020-12-02 12:34

    Yes:

    if (ex.InnerException == null) {
        // then it's null
    }
    
    0 讨论(0)
  • 2020-12-02 12:35

    With C# 6.0 you can use:

    string message = exception.InnerException?.Message ?? "";

    This line of code is similar to:

    string message = exception.InnerException == null ? "" : exception.InnerException.Message.

    https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

    http://blogs.msdn.com/b/jerrynixon/archive/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator.aspx

    0 讨论(0)
  • 2020-12-02 12:41

    With this code you will be sure that you did't lose any inner exception messages

    catch (Exception exception)
    {
       Logger.Error(exception.Message);
       while (exception.InnerException != null)
       {
           exception = exception.InnerException;
           Logger.Error(exception);
       }
    }
    
    0 讨论(0)
提交回复
热议问题