diff options
author | Howard van Rooijen <Howard.vanRooijen@endjin.com> | 2015-02-04 21:49:29 +0000 |
---|---|---|
committer | Howard van Rooijen <Howard.vanRooijen@endjin.com> | 2015-02-06 07:23:55 +0000 |
commit | 2705013d2b58d0e614205606c87c4ad2ecec8259 (patch) | |
tree | 93e610e85a2bf722bc0ce2581a42e386e84ccf2a /SendGrid/SendGridMail/Transport/ErrorChecker.cs | |
parent | 6354302c92e8994b44ae8fc89a992ad4ffca5b6d (diff) | |
download | sendgrid-csharp-2705013d2b58d0e614205606c87c4ad2ecec8259.zip sendgrid-csharp-2705013d2b58d0e614205606c87c4ad2ecec8259.tar.gz sendgrid-csharp-2705013d2b58d0e614205606c87c4ad2ecec8259.tar.bz2 |
Refactor error handling. Add test for checking for bad username / password scenario
Diffstat (limited to 'SendGrid/SendGridMail/Transport/ErrorChecker.cs')
-rw-r--r-- | SendGrid/SendGridMail/Transport/ErrorChecker.cs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/SendGrid/SendGridMail/Transport/ErrorChecker.cs b/SendGrid/SendGridMail/Transport/ErrorChecker.cs new file mode 100644 index 0000000..035d2b8 --- /dev/null +++ b/SendGrid/SendGridMail/Transport/ErrorChecker.cs @@ -0,0 +1,57 @@ +namespace SendGrid +{ + using System; + using System.IO; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + using System.Xml; + + using Exceptions; + + public static class ErrorChecker + { + public static void CheckForErrors(HttpResponseMessage response) + { + CheckForErrors(response, response.Content.ReadAsStreamAsync().Result); + } + + public static async Task CheckForErrorsAsync(HttpResponseMessage response) + { + CheckForErrors(response, await response.Content.ReadAsStreamAsync()); + } + + private static void CheckForErrors(HttpResponseMessage response, Stream stream) + { + if (response.StatusCode != HttpStatusCode.OK) + { + using (var reader = XmlReader.Create(stream)) + { + while (reader.Read()) + { + if (!reader.IsStartElement()) + { + continue; + } + + switch (reader.Name) + { + case "result": + continue; + case "message": + continue; + case "errors": + reader.ReadToFollowing("error"); + var message = reader.ReadElementContentAsString("error", reader.NamespaceURI); + throw new InvalidApiRequestException(response.StatusCode, new[] { message }, response.ReasonPhrase); + case "error": + throw new ProtocolViolationException(); + default: + throw new ArgumentException("Unknown element: " + reader.Name); + } + } + } + } + } + } +}
\ No newline at end of file |