Solved

C#, stop http server errors from throwing exceptions

Posted on 2011-02-14
7
1,079 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:PiZzL3
Comment Utility
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
Comment Utility
Excellent help! Thanks!
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
>>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
Comment Utility
Thank you for the second example!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
asp.net bundle 8 32
Limiting string to two deciamls 18 30
getting id from database 5 23
Showdialog 8 20
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

762 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