SRDebugApiUtil.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using SRF;
  6. namespace SRDebugger.Internal
  7. {
  8. public static class SRDebugApiUtil
  9. {
  10. public static string ParseErrorException(WebException ex)
  11. {
  12. if (ex.Response == null)
  13. {
  14. return ex.Message;
  15. }
  16. string result;
  17. try
  18. {
  19. string response = SRDebugApiUtil.ReadResponseStream(ex.Response);
  20. result = SRDebugApiUtil.ParseErrorResponse(response, "Unexpected Response");
  21. }
  22. catch
  23. {
  24. result = ex.Message;
  25. }
  26. return result;
  27. }
  28. public static string ParseErrorResponse(string response, string fallback = "Unexpected Response")
  29. {
  30. string result;
  31. try
  32. {
  33. Dictionary<string, object> dictionary = (Dictionary<string, object>)Json.Deserialize(response);
  34. string text = string.Empty;
  35. text += dictionary["errorMessage"];
  36. object obj;
  37. if (dictionary.TryGetValue("errors", out obj) && obj is IList<object>)
  38. {
  39. IList<object> list = obj as IList<object>;
  40. foreach (object arg in list)
  41. {
  42. text += "\n";
  43. text += arg;
  44. }
  45. }
  46. result = text;
  47. }
  48. catch
  49. {
  50. if (response.Contains("<html>"))
  51. {
  52. result = fallback;
  53. }
  54. else
  55. {
  56. result = response;
  57. }
  58. }
  59. return result;
  60. }
  61. public static bool ReadResponse(HttpWebRequest request, out string result)
  62. {
  63. bool result2;
  64. try
  65. {
  66. WebResponse response = request.GetResponse();
  67. result = SRDebugApiUtil.ReadResponseStream(response);
  68. result2 = true;
  69. }
  70. catch (WebException ex)
  71. {
  72. result = SRDebugApiUtil.ParseErrorException(ex);
  73. result2 = false;
  74. }
  75. return result2;
  76. }
  77. public static string ReadResponseStream(WebResponse stream)
  78. {
  79. string result;
  80. using (Stream responseStream = stream.GetResponseStream())
  81. {
  82. using (StreamReader streamReader = new StreamReader(responseStream))
  83. {
  84. result = streamReader.ReadToEnd();
  85. }
  86. }
  87. return result;
  88. }
  89. }
  90. }