Re throw exception - c#

I have the following code:
public static string Get(string requestUri)
{
try
{
return GetStringAsync(requestUri).Result;
}
catch (AggregateException aggregateException)
{
Console.WriteLine(aggregateException);
throw;
}
}
When the try block throws an exception, the program goes as it should in the catch block and displays the information about the error.
The problem is that once arrived at the rethrow, the debugger stops and raises me again the same exception but at the same level, despite it is supposed to go up one level in the stack...
I did not find a solution on the Internet, all examples correspond to my code.
EDIT
Your solution is working for the code above, but I have another which doesn't work too :
public static string Post(string requestUriString, string s)
{
var request = (HttpWebRequest)WebRequest.Create(requestUriString);
var data = Encoding.ASCII.GetBytes(s);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
}
catch (WebException webException)
{
Console.WriteLine(webException);
throw;
}
}

The issue is the way AggregateException is handled; change your method to an async method (which eliminates the AggregateException wrapper), and throw will work as expected:
public static async Task<string> Get(string requestUri)
{
try
{
return await GetStringAsync(requestUri);
}
catch (Exception exception) // Or, specify the expected exception type
{
Console.WriteLine(exception);
throw; // can be caught in the calling code
}
}

Related

I'm not getting exception but when using a break point i see exception on the stream how can i solve it?

async Task<Image> GetImageAsync(string url)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//On worker thread
var response = await request.GetResponseAsync() as HttpWebResponse;
//Back on calling thread
var responseStream = GetCompressedStream(response);
if (responseStream != null)
return Image.FromStream(responseStream);
}
catch(Exception eee)
{
string myerropr = eee.ToString();
}
return null;
}
And
private static Stream GetCompressedStream(HttpWebResponse response)
{
try
{
var stream = response.GetResponseStream();
if (response.ContentEncoding.ToLower().Contains("gzip"))
return new GZipStream(stream, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
return new DeflateStream(stream, CompressionMode.Decompress);
}
catch(EndOfStreamException ee)
{
string myer = ee.ToString();
}
return null;
}
On the var stream when i use a breakpoint i see at Length:
Length = 'stream.Length' threw an exception of type
'System.NotSupportedException'
Same exception on Position.
Then in the end both methods return null.
I couldn't catch the exceptions only when using break point i see them.
I recommend reading this article regarding the NotSupportedException.
In your case, the exceptions are only happening internally (you can only see them whilst debugging), so you don't really need to worry about them.

How to catch exception?

I am trying to call api and check its response, but when ever some wrong value is passed it stops the program. I want to add exception during request and response but not sure how to write in function.
This is how i call my REST call
public dynamic APICalls(JObject ljson, string endpoints, string method)
{
var httpReq = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpReq.GetRequestStream()))
{
streamWriter.Write(ljson);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
var result = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
THis is code for request
public dynamic HttprequestObject(string endpoints, string method)
{
string url = Settings.API_TEST_VALUE + endpoints;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method;
return httpWebRequest;
}
And right before request and right after response i want to catch exception.
At this point i have to catch exception
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
If some one gives me hint how to catch that before it stops program.
There are 400, 401,402 errors, if something is wrong API sends json
For instance, while creating user :-- Email id already exists
But that points stops json and stops program..
Using try catch it will stop program, I want it to run and want to receive resposne.
Actually, API will send error .
For instance, status will be ;---401 UNAUTHORIZED
and resposnse will be
{ "reason": "Email already registered.", "success": false }
I am changed my code and
HttpWebResponse httpResponse;
try
{
//HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpReq.GetResponse();
httpResponse = (HttpWebResponse)httpReq.GetResponse();
//myHttpWebResponse.Close();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
This is the new code, but I m not getting Json as return value, So i can show specific error.
For below Json what should I write?
{ "reason": "Email already registered.", "success": false }
please I m new to c# and if something is not clear please modify or ask question?
thank you
What you're looking for is called a try-catch statement:
try
{
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
}
catch (WebException e)
{
// Here is where you handle the exception.
}
Using WebException as the type in the catch statement means only exceptions of that particular type will be caught.
In case an exception occurs, the e variable will contain exception details, such as a message passed from the method which three the exception and any inner exceptions encapsulated inside.
You can handle your web exceptions to get HttpStatusCode and Response Message this way:
public void SendAndGetResponseString()
{
try
{
// Here you call your API
}
catch (WebException e)
{
var result = GetResponceFromWebException(e);
if (result != null){
//
// Here you could use the HttpStatusCode and HttpResponseMessage
//
}
throw;
}
catch (Exception e)
{
// log exception or do nothing or throw it
}
}
private HttpRequestResponce GetResponceFromWebException(WebException e)
{
HttpRequestResponce result = null;
if (e.Status == WebExceptionStatus.ProtocolError)
{
try
{
using (var stream = e.Response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var responseString = reader.ReadToEnd();
var responce = ((HttpWebResponse) e.Response);
result = new HttpRequestResponce(responseString, responce.StatusCode);
}
}
}
}
catch (Exception ex)
{
// log exception or do nothing or throw it
}
}
return result;
}
public class HttpRequestResponce {
public HttpStatusCode HttpStatusCode { get;set; }
public string HttpResponseMessage {get;set;}
public HttpRequestResponce() { }
public HttpRequestResponce(string message, HttpStatusCode code)
{
HttpStatusCode=code;
HttpResponseMessage=message;
}
}
You encapsulate whatever method call or code block you want to prevent from throwing unhandled exceptions.
try
{
// code here
}
catch (Exception)
{
// here you may do whatever you want to do when an exception is caught
}
Ok,Finally I am able to Solve this.. Thanks everyone for you help.
This worked for me. I think I was not reading whole response.. So some how I think I realized and now its working ..
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

C# Exceptions Not Being Handled

The following code is called via the browser and if an exception occurs that exception is never caught by the 'Try Catch' but instead the exception is reported to the screen. I have tried running without debug as well as turning off CLR errors. Any suggestions would be appreciated:
public string GetUrl(string url)
/*Grab remote page */
{
string target = string.Empty;
HttpWebRequest httpWebRequest = null;
HttpWebResponse response = null;
StreamReader streamReader = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)httpWebRequest.GetResponse();
streamReader = new StreamReader(response.GetResponseStream(), true);
target = streamReader.ReadToEnd();
}
catch (WebException e)
{
Console.WriteLine("Error:GetUrl()");
Console.WriteLine("\n{0}", e.Message);
Console.WriteLine("\n{0}", e.Status);
}
finally
{
streamReader.Close();
response.Close();
}
return target;
}
You are only catching webexceptions, any other exception is not caught.
It can throw more exceptions see here :
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse%28v=vs.110%29.aspx
Add one more catch block before finally block and trap base Excaption. It will catch all type of error occurred and not caught in earlier catch blocks.

HttpWebRequest proper exception handling

So I'm using the HttpWebRequest API in the System.Net assembly but because C# has no checked exceptions, I'm not sure where to put my try-catch blocks to properly handle inevitable exceptions caused by common things like a network error. You know, in Java we would call these plain old checked IOExceptions.
This is what I have so far. Are my try-catch blocks properly set up to handle network errors? Am I wrapping the right method calls? Looking at the documentation, I think they are right, but I need a second pair of eyes.
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
HttpWebRequest getRequestRequest = (HttpWebRequest) getRequestResult.AsyncState;
try
{
Stream requestStream = getRequestRequest.EndGetRequestStream(getRequestResult);
requestStream.Write(parametersData, 0, parametersData.Length);
requestStream.Dispose();
getRequestRequest.BeginGetResponse(getResponseResult =>
{
HttpWebRequest getResponseRequest = (HttpWebRequest)getResponseResult.AsyncState;
try
{
WebResponse response = getResponseRequest.EndGetResponse(getRequestResult);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string jsonString = reader.ReadToEnd();
reader.Dispose();
JObject jsonObject = JObject.Parse(jsonString);
onResult(StatusCode.Ok, jsonObject);
}
catch (WebException)
{
onResult(StatusCode.NetworkError);
}
}, getRequestRequest);
}
catch (IOException)
{
onResult(StatusCode.NetworkError);
}
}, request);
First off, unless there's some reason that you need to use HttpWebRequest, then you're better off using WebClient.UploadString instead, or any of WebClient's other UploadXXX overloads for uploading name/value pairs, files, binary data, etc. This will be much easier for you, and easier to troubleshoot and debug. Also, another problem is that you're treating exceptions during JSON parsing or during your onResult handler error as network errors.
Below are three examples of using WebClient that you might want to try: a synchronous version, an "old-style" async version, and a "new-style" async version that uses async/await. All three versions also try to fix the exception handling issue that I noted above. If you don't need async support, then the first version will be easiest.
static void PostSync (string url, string parametersData)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // or "application/json" or ...
try
{
string htmlResult = wc.UploadString(url, parametersData); // or UploadValues, UploadFile, ...
JObject jsonObject = null;
try
{
jsonObject = JObject.Parse(htmlResult);
}
catch (JsonException ex)
{
onResult(StatusCode.JsonError);
}
onResult(StatusCode.Ok, jsonObject);
}
catch (System.Net.WebException ex)
{
onResult(StatusCode.NetworkError);
}
}
}
static void PostAsync(string url, string parametersData)
{
using (WebClient wc = new WebClient())
{
wc.UploadStringCompleted += (Object sender, UploadStringCompletedEventArgs e) =>
{
if (e.Error != null)
onResult(StatusCode.NetworkError);
JObject jsonObject = null;
try
{
jsonObject = JObject.Parse(e.Result);
}
catch (JsonException ex)
{
onResult(StatusCode.JsonError);
}
onResult(StatusCode.Ok, jsonObject);
};
try
{
wc.UploadStringAsync(new Uri(url, UriKind.Absolute), parametersData);
}
catch (System.Net.WebException ex)
{
onResult(StatusCode.NetworkError);
}
}
}
static async void PostTaskAsync(string url, string parametersData)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // or "application/json" or ...
try
{
string htmlResult = await wc.UploadStringTaskAsync(url, parametersData); // or UploadValues, UploadFile, ...
JObject jsonObject = null;
try
{
jsonObject = JObject.Parse(htmlResult);
}
catch (JsonException ex)
{
onResult(StatusCode.JsonError);
}
onResult(StatusCode.Ok, jsonObject);
}
catch (System.Net.WebException ex)
{
onResult(StatusCode.NetworkError);
}
}
}

Catching HttpWebRequest Timeout

public int loginEmail(string email, string password)
{
HttpWebRequest request = null;
string responseStr = null;
string Email = email;
string Pass = password;
UTF8Encoding encoding = new UTF8Encoding();
string postData = "PostData";
byte[] data = encoding.GetBytes(postData);
request = (HttpWebRequest)WebRequest.Create("url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
request.KeepAlive = false;
request.Proxy = null;
request.ServicePoint.ConnectionLimit = 1000;
request.ContentLength = data.Length;
request.Timeout = 5000;
request.ServicePoint.ConnectionLeaseTimeout = 5000;
request.ServicePoint.MaxIdleTime = 5000;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseStr = response.Headers["Set-Cookie"];
}
}
catch
{
return 1;
}
string[] cooktemp;
string[] seperatortemp = new string[] { ";" };
cooktemp = responseStr.Split(seperatortemp, StringSplitOptions.None);
LoginHeaders[0] = cooktemp[0] + ";";
return 0;
}
This code runs just fine, but sometimes the request does not get a response back. When the request doesn't get a response back the program will hang and then finally it will give a timeout error that crashes the program. All I am trying to do right now is just catch the timeout error so I can handle it, but nothing seems to be catching it.
It is most likely timing out in GetRequestStream(). The documentation specifically states that it may throw WebException if the time-out period for the request expired.
So include that block of code inside your try/catch and you should be able to catch it.
This is an old thread, but an issue which I also hit today.
What I didn't realise is that if you have a web service which, say, attempts to write to a file which is locked... then having the code in a simple try..catch is not enough.
You must specifically have a catch which handles WebExceptions.
try
{
// Run your web service code
}
catch (WebException ex)
{
// Handle a WebException, such as trying to write to a "locked" file on the network
}
catch (Exception ex)
{
// Handle a regular Exception
}
I always thought that a WebException was a type of Exception, so these would get caught by this catch handler:
catch (Exception ex)
{
// Handle a regular Exception
}
It doesn't.
So to avoid your code throwing "Request timed out" messages, with no suggestion about what caused them, do remember to add these second catch handler.
Btw, on my web services tutorial, here's the code I recommend, which looks out for Exceptions, and returns them in the Response header:
try
{
// Put your code in here
}
catch (WebException ex)
{
// Return any exception messages back to the Response header
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = ex.Message.Replace("\r\n", "");
return null;
}
catch (Exception ex)
{
// Return any exception messages back to the Response header
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = ex.Message.Replace("\r\n", "");
return null;
}
try { ... }
catch (System.Net.WebException sne)
{
MessageBox.Show(req.Timeout.ToString());
}
I think the timeout will always be "5000" no matter what.
If you tell it "timeout is 5 seconds" it will always try for 5 seconds before giving up.

Categories

Resources