I have an API call that returns a query string in json format. Occasionally I get the following response
"<html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>502 Bad Gateway</h1></center>\r\n</body>\r\n</html>\r\n"
My code interpreting this response is
string jsonOrdersString = bitmexApi.GetOpenZTOrders(25);//
List<OrderRecord> newList = JsonConvert.DeserializeObject<List<OrderRecord>>(jsonOrdersString);
This works the majority of the time, until I get an error 502 error. How can I run a check on my json string to see if there is an error and handle it? Its also worth noting that I have many Deserialize Processes in this program, so it would be nice to keep this error handling efficent.
Any help is appreciated, I am new to c# and json and this issue is holding up this project.
Thanks!
Edit: The GetOpenZTOrderS() function calls this Query function. How can I modify this to get also return the status code?
private string Query(string method, string function, Dictionary<string, string> param = null, bool auth = false, bool json = false)
{
string paramData = json ? BuildJSON(param) : BuildQueryData(param);
string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
string postData = (method != "GET") ? paramData : "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(domain + url);
webRequest.Method = method;
if (auth)
{
string expires = GetExpires().ToString();
string message = method + url + expires + postData;
byte[] signatureBytes = hmacsha256(Encoding.UTF8.GetBytes(apiSecret), Encoding.UTF8.GetBytes(message));
string signatureString = ByteArrayToString(signatureBytes);
webRequest.Headers.Add("api-expires", expires);
webRequest.Headers.Add("api-key", apiKey);
webRequest.Headers.Add("api-signature", signatureString);
}
try
{
if (postData != "")
{
webRequest.ContentType = json ? "application/json" : "application/x-www-form-urlencoded";
var data = Encoding.UTF8.GetBytes(postData);
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
if (response == null)
throw;
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
}
}
}