Created
September 25, 2013 06:02
-
-
Save PaulGreenwell/6695668 to your computer and use it in GitHub Desktop.
C# example for extracting the content from AccountRight API SDK error messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void OnError(Uri uri, Exception ex) | |
{ | |
//Display the formatted message | |
switch (ex.GetType().Name) | |
{ | |
case "WebException": | |
MessageBox.Show(FormatMessage((WebException) ex)); | |
break; | |
case "ApiCommunicationException": | |
MessageBox.Show(FormatMessage((WebException) ex.InnerException)); | |
break; | |
case "ApiOperationException": | |
MessageBox.Show(ex.Message); | |
break; | |
default: | |
MessageBox.Show(ex.Message); | |
break; | |
} | |
HideSpinner(); | |
} | |
private string FormatMessage(WebException webEx) | |
{ | |
var responseText = new StringBuilder(); | |
responseText.AppendLine(webEx.Message); | |
responseText.AppendLine(); | |
// Call method 'GetResponseStream' to obtain stream associated with the response object | |
WebResponse response = webEx.Response; | |
Stream receiveStream = response.GetResponseStream(); | |
Encoding encode = Encoding.GetEncoding("utf-8"); | |
// Pipe the stream to a higher level stream reader with the required encoding format. | |
var readStream = new StreamReader(receiveStream, encode); | |
var read = new Char[257]; | |
// Read 256 charcters at a time . | |
int count = readStream.Read(read, 0, 256); | |
responseText.AppendLine("HTML..."); | |
while (count > 0) | |
{ | |
// Dump the 256 characters on a string and display the string onto the console. | |
var str = new String(read, 0, count); | |
responseText.Append(str); | |
count = readStream.Read(read, 0, 256); | |
} | |
responseText.Append(""); | |
// Release the resources of stream object. | |
readStream.Close(); | |
// Release the resources of response object. | |
response.Close(); | |
return responseText.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment