ThrowIfErrors... regex is incorrect?

Jul 5, 2008 at 4:17 PM
Hi,

I think the ThrowIfErrors regex may be incorrect. I was testing adding Content-MD5 to PUT requests and was getting an exception "The remote server returned an error: (400) Bad Request". During debugging I could see the XML error for bad MD5... but this was not being handled by the ThrowIfError logic. Here's a bad MD5 error:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InvalidDigest</Code>
<Message>The Content-MD5 you specified was an invalid.</Message>
<RequestId>xxx</RequestId>
<Content-MD5>qT6fm08+4TRQ62mX8IkC1Q==a</Content-MD5>
<HostId>xxx</HostId>
</Error>

Here's the guts of ThrowIfError:
Match errorMatcher = Regex.Match(responseString,
    "(<Error><Code>(.*)</Code><Message>(.*)</Message></Error>).*(<Error>)?");
if (errorMatcher.Success)
{
    String xml = errorMatcher.Groups[2].Value;
    String code = errorMatcher.Groups[3].Value;
    String message = errorMatcher.Groups[4].Value;
    ThreeSharpException ex = new ThreeSharpException(message, httpWebResponse.StatusCode, code, null, xml);
    throw ex;
}

If I read the regex right it looks like an error "ends" in "</Message></Error>"... but that clearly isn't always the case.

Adjusting the code to:
Match errorMatcher = Regex.Match(responseString,
    "(<Error><Code>(.*)</Code><Message>(.*)</Message>).*(</Error>)?");
if (errorMatcher.Success)
{
    String xml = errorMatcher.Groups[0].Value;
    String code = errorMatcher.Groups[2].Value;
    String message = errorMatcher.Groups[3].Value;
    ThreeSharpException ex = new ThreeSharpException(message, httpWebResponse.StatusCode, code, null, xml);
    throw ex;
}

This now appears to handle errors correctly. It no longer matches on "</Message></Error>"... just "</Message>".

Also the match Groups didn't seem to be correct... not sure if that's because of my changes or not (I don't think so... but I really haven't done any before/after testing of my change).

Regards,

Rob
Coordinator
Aug 11, 2008 at 6:48 PM
Hi Rob,
  Your analysis was spot on!  I've included your fix in Release 1.4

Thanks,
Joel Wetzel
Affirma Consulting