?
Solved

C#, stop http server errors from throwing exceptions

Posted on 2011-02-14
7
Medium Priority
?
1,117 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 1000 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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 

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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

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…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Screencast - Getting to Know the Pipeline
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses

755 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