Solved

C#, stop http server errors from throwing exceptions

Posted on 2011-02-14
7
1,080 Views
Last Modified: 2013-12-17
How do I stop exceptions like this from being thrown?

System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.

I assume it will throw an exception for all sorts of other http errors (404, 500, etc...). I don't want my program to do this. I would like it to get a page just like you would see in a web browser where it shows you the error as HTML and has the stats in the header.

The only way I can think to do this would to put a more specialized web exception catch in front of the general exception catch and ignore them or generate some special flag variable to use later. I'm unsure of how this would affect other errors that may happen though.. So I'm hesitant to do this. What I really want is something like "Request.ReturnHttpStatusException = false;". I think that's wishful thinking though.

Thanks for any help.
0
Comment
Question by:PiZzL3
  • 4
  • 3
7 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34892007
The only way I can think to do this would to put a more specialized web exception catch in front of the general exception catch and ignore them or generate some special flag variable to use later

Precisely.

Are you using the WebBrowser control, or HttpWebRequests?
0
 

Author Comment

by:PiZzL3
ID: 34892543
What specific exception handles only http server errors? I don't want it to affect anything else.

I'm using this:
HttpWebRequest Request;
Request = (HttpWebRequest)WebRequest.Create(ut.url);

Open in new window

0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 250 total points
ID: 34897224
The documentation will generally tell you what exceptions are thrown under what conditions: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx

In this case you want to catch WebException.  The documentation for WebException (http://msdn.microsoft.com/en-us/library/system.net.webexception.aspx) indicates we should examine it's Response property, and the documentation for WebException.Response has details and examples (http://msdn.microsoft.com/en-us/library/system.net.webexception.response.aspx).

Here's a kind of pointless Console application example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/no-such-file.html");
			HttpWebResponse response = null;

			try
			{
				response = (HttpWebResponse)request.GetResponse();
				Console.Write(new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd());
			}
			catch (WebException ex)
			{
				if (ex.Status == WebExceptionStatus.ProtocolError)
				{
					HttpWebResponse errorResponse = ex.Response as HttpWebResponse;
					if (errorResponse != null)
					{
						switch (errorResponse.StatusCode)
						{
							case HttpStatusCode.NotFound:
								Console.WriteLine("The requested page couldn't be found.");
								break;
							case HttpStatusCode.Unauthorized:
								Console.WriteLine("You are not permitted to view this page.");
								break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("An unknown error occurred: {0}", ex.Message);
			}

			Console.ReadKey();
		}
	}
}

Open in new window




I would like it to get a page just like you would see in a web browser where it shows you the error as HTML and has the stats in the header
The web browsers themselves are responsible for creating this pretty error message for the user, and since you're writing the browser in this case you'll have to write code to create such a page yourself; there is nothing intrinsicly in HTTP or the WebRequest classes that'll do this for you.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:PiZzL3
ID: 34899718
The web browsers themselves are responsible for creating this pretty error message for the user, and since you're writing the browser in this case you'll have to write code to create such a page yourself; there is nothing intrinsicly in HTTP or the WebRequest classes that'll do this for you.

I have to disagree to a certain extent... I have a great deal of experience with servers/php/apache/etc. I know they do generate error pages for all types of errors. You can even set custom error pages. I believe this is what confused me the most. I wanted that error page returned as a successful request. I didn't understand how normal error could return an exception. I think C# just detects it in the header and throws the error. I also realize that this isn't always the case and the server may not return an error page at all. I suppose this is ok then.

You're solution will actually work better than I was thinking it would (it has a great deal of advantages in the way it forces you to process the information and saves me the trouble of writing code to determine if the request failed or not). I have this odd habit of considering exceptions as really bad errors that will always break code. I guess that's not always the case and I'll have to get over that. This try catch deal is still very new to me and I had a difficult time grasping it's purpose at first. Now I see how useful it can be.

Thank you for your help!
0
 

Author Closing Comment

by:PiZzL3
ID: 34899722
Excellent help! Thanks!
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34899806
>>they do generate error pages for all types of errors

Sorry...you're right, I got those stupid Internet Explorer error pages that it pulls from a local DLL stuck in my head.

At any rate, you can just check (following the example above) if errorResponse.ContentLength > 0 and/or errorResponse.ContentType = "text/html" and use errorResponse.GetResponseStream() to read the error page, same as you would a successful page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/no-such-file.html");
			HttpWebResponse response = null;

			try
			{
				response = (HttpWebResponse)request.GetResponse();
				Console.Write(new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd());
			}
			catch (WebException ex)
			{
				if (ex.Status == WebExceptionStatus.ProtocolError)
				{
					HttpWebResponse errorResponse = ex.Response as HttpWebResponse;
					if (errorResponse != null)
					{
						switch (errorResponse.StatusCode)
						{
							case HttpStatusCode.NotFound:
								if (errorResponse.ContentLength > 0)
									Console.Write(new StreamReader(errorResponse.GetResponseStream()).ReadToEnd());
								else
									Console.WriteLine("The requested page couldn't be found.");
								break;
							case HttpStatusCode.Unauthorized:
								Console.WriteLine("You are not permitted to view this page.");
								break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("An unknown error occurred: {0}", ex.Message);
			}

			Console.ReadKey();
		}
	}
}

Open in new window

0
 

Author Comment

by:PiZzL3
ID: 34899875
Thank you for the second example!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Loop not working 29 47
SQL Exceptions 3 39
rest webservice call over https via c# 6 25
C#.NET and microsoft certification. 3 34
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now