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.
Related
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
}
}
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.
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);
}
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.
Uri URL2 = new Uri(#"http://www......com");
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(URL2);
request2.Timeout = 10000;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
I am making webrequest with the codes above. When I write a stupid url such as www.oiasjdilasod.com it throws exception; however when an existing page is not available for few hours I cannot get this exception. it doesn't throw any exception and stop running.
When this page is not available i tried at internet explorer, it showed page can not be found http 400 bad request.
Do you have any suggestions how to catch this exception?
The fact that you are getting a response back from the server means that it's available, it's just not working properly - therefore the request is made and doesn't time out because the server has responded.
It's just not the response you wanted.
Instead, you should check the StatusCode property.
if(response2.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Site is responding incorrectly!");
}
i had the same problem before and
catch(WebException e)
{
Console.WriteLine(e.toString());
}
will solve it
This Piece of Code Worked for me
try
{
Uri URL2 = new Uri(#"http://www.*****.com");
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(URL2);
request2.Timeout = 100;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
}
catch (WebException e)
{
MessageBox.Show(e.Message.ToString());
}
What exception are you throwing? A regular Exception won't do, it has to be a WebException.
...
catch(WebException e)
{
Console.WriteLine("Error: "+ e.Status);
}
EDIT:
How about a Timeout Exception (Along with the WebException)?
catch (TimeoutException e)
{
Console.WriteLine(e);
}
catch(WebException e)
{
Console.WriteLine("Error: "+ e.Status);
}