Recording error messages from an exception

How do I shorten these if else statements? As you can see, those elses are repeated.

if (exception.InnerException != null)
{
if (!string.IsNullOrEmpty(exception.InnerException.Message))
{
errorMessage = exception.InnerException.Message;
}
else if (!string.IsNullOrEmpty(exception.Message))
{
errorMessage = exception.Message;
}
else
{
errorMessage = exception.ToString();
}
}
else if (!string.IsNullOrEmpty(exception.Message))
{
errorMessage = exception.Message;
}
else
{
errorMessage = exception.ToString();
}

• If this is something you use a lot, maybe consider making this an extension method that takes in an Exception and returns a string. – jrh Jan 2 '18 at 12:49
• Just as a suggestion, at work we've adopted the maybe lesser known string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty , just to counter those edge cases where any other white-space character was used instead of an empty string. – AsheraH Jan 2 '18 at 13:51

In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):

ver errorMessage =  exception.InnerException?.Message ??
exception.Message ??
exception.ToString();


Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...

If you fear that situation, you can always create an extension method for strings that will return null for empty strings:

public static string NullIfEmpty(this string str)
{
return string.IsNullOrEmpty(str) ? null : str;
}


and then use it like this:

ver errorMessage =  exception.InnerException?.Message?.NullIfEmpty() ??
exception.Message?.NullIfEmpty() ??
exception.ToString();

• it is quite possible to set an exception to have an empty string :) e.g. throw new Exception(). Nice code though. – zaitsman Jan 2 '18 at 11:22
• @zaitsman Of course it's possible, it's just not very useful... that's why you don't see them so often. In fact, in 18 years of programming in various languages and technologies, I've never encountered an error that had no message. – Zohar Peled Jan 2 '18 at 11:36

Assuming you have at least c# 6 (and thus, the null propagation operator), you can simplify it like this:

        if (!string.IsNullOrEmpty(exception?.InnerException?.Message))
{
errorMessage = exception.InnerException.Message;
}
else if (!string.IsNullOrEmpty(exception?.Message))
{
errorMessage = exception.Message;
}
else
{
errorMessage = exception?.ToString();
}


This will handle anything being null along the way.

You can use GetBaseException to get the lowest level exception.

var message = exception.GetBaseException()?.Message;
if(string.IsNullOrEmpty(message))
message = exception.ToString();