summaryrefslogtreecommitdiffstats
path: root/SendGrid/SendGridMail/Transport/ErrorChecker.cs
blob: 035d2b80c0995522b3115dcb7d1a0394468cf672 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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);
                        }
                    }
                }
            }
        }
    }
}