HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Helper method to extract a specific string from long message

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodhelpermessagelongextractspecificfromstring

Problem

private string ExtractExceptionMesssage(string exceptionMessage)
{
    const string startWord = "Message>";
    int startWordLength = startWord.Length;
    const string endWord = "/Message>";
    var length = exceptionMessage.Length;
    int index = 0;
    var sb = new StringBuilder();

    while (index < length)
    {
        var startIndex = exceptionMessage.IndexOf(startWord, index, StringComparison.Ordinal);
        if (startIndex < 0)
            break;
        var endIndex = exceptionMessage.IndexOf(endWord, startIndex, StringComparison.Ordinal);
        if (endIndex < 0)
        {
            break;
        }
        var len = endIndex - 4 - (startIndex + startWord.Length); // -4 is ".<"
        sb.AppendLine(exceptionMessage.Substring(startIndex + startWordLength, len));
        index = endIndex + endWord.Length + 1;
    }

    if (sb.Length == 0) sb.Append("Unknown error");
    return sb.ToString();
}


I'll appreciate any idea of how to make it better

Solution

Consistent style

You kind of mixing your styles with curly braces - your indentation is inconsistent, and for two duplicate ifs with single statement you once omit the braces, and on the other not. Choose a style, and stick to it - it will make your code more readable

Magic numbers

You made a curious choice to omit the "&lt;" from you start and end indicators, which made you add the mysterious - 4 to your len calculation. This is a major maintenance issue, since tomorrow you will want to extract with unescaped text, where the "&lt;" will be reduced to "<", and your code will stop working...

Use the powers of the tools at hand

Your solution could be much simpler if you used Regex to solve it:

private string ExtractExceptionMesssage(string exceptionMessage) {
    string pattern = @"<Message>(.+?)lt;/Message>";
    Regex rgx = new Regex(pattern);
    var sb = new StringBuilder();
    MatchCollection matches = rgx.Matches(input);
    if (matches.Count > 0) {
       foreach (Match match in matches) {
         sb.AppendLine(match.Value);
       }
    } else {
       return "Unknown error";
    }
    return sb.ToString();
}

Code Snippets

private string ExtractExceptionMesssage(string exceptionMessage) {
    string pattern = @"&lt;Message&gt;(.+?)lt;/Message&gt;";
    Regex rgx = new Regex(pattern);
    var sb = new StringBuilder();
    MatchCollection matches = rgx.Matches(input);
    if (matches.Count > 0) {
       foreach (Match match in matches) {
         sb.AppendLine(match.Value);
       }
    } else {
       return "Unknown error";
    }
    return sb.ToString();
}

Context

StackExchange Code Review Q#45292, answer score: 4

Revisions (0)

No revisions yet.