Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C#, stop http server errors from throwing exceptions

Posted on 2011-02-14
7
Medium Priority
?
1,112 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 

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

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

609 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