Link to home
Start Free TrialLog in
Avatar of PiZzL3
PiZzL3Flag for United States of America

asked on

C#, stop http server errors from throwing exceptions

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.
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

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?
Avatar of PiZzL3

ASKER

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

ASKER CERTIFIED SOLUTION
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PiZzL3

ASKER

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!
Avatar of PiZzL3

ASKER

Excellent help! Thanks!
>>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

Avatar of PiZzL3

ASKER

Thank you for the second example!