Skip navigation.

ASP.NET Custom Error Pages

Comment permalink 1 jon dalberg |
Great article! My question is: What happens when i set the Response.StatusCode programmatically? For example, I have configured a custom error page for status code 404 named 404.aspx. If I set the Response.StatusCode=404 nothing happens and the page continues to process. Next I tried calling Response.End() which caused the generic 404 page, not my 404.aspx page. Response.Flush() caused the generic ASP.Net 404 error page instead of my 404.aspx page. Any ideas why it would behave this way?

Thanks.
Comment permalink 2 Milan Negovan |
Good question. I've played with the StatusCode property a little bit and haven't had much luck figuring it out. I'll post an update if I can trace it through the disassembled code.
Comment permalink 3 Shawn C |
Try trapping 401's - Not possible.
Comment permalink 4 Mike |
nice article, thank you!
Comment permalink 5 Floook |
Thanks for the data. I just got an exception I was not able to handle today because it didn't say what file or line it occurred in.

I added your function to my class and voila! It told me what line the exception occurred at and I was able to debug the script immediately.

Thanks a lot!
Comment permalink 6 jkgreer |
lately i've been using elmah.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/elmah.asp
for server wide/cluster exception handling you can't beat it. there is a sql provider and by adding a few lines to your machine.config and one assembly to the gac the entire machine logs. i've built real time reports and graphs showing when servers or apps are going balistic. then i try and code very aggressivly for a resonable (documented) set of behavior to avoid exceptions and let the serious ones fall through and fix the true mistakes as i see them. throwing and catching exceptions can be a pretty expensive operation.

i am curious though, if anyone has found a really clean way to balance what errors should be globally catched and what errors get translated into a user friendly displayable error. There always seems to be a gray area of what should fall through and what should be reported back to a user.
Comment permalink 7 Monica |
Very nice article! I'm trying the CustomErrors4 and instead of raising a general exception, I'm trying to cause the page not found with:

Server.Transfer("NoPage.aspx");

But it keeps going to the GeneralError.aspx.
Comment permalink 8 Marcus |
I've managed to trap the .htm and .html files by adding them into my Application mappings, however I'm still wanting to trap other errors, such as folder names, and word documents. If I go to http://www.mysite.com/foldername (and presuming foldername doesn't exist) I get the standard 404, not my custom 404.

Likewise for word documents, something tells me I probably shouldn't map .doc, .pdf, .gif, .jpg, .png all to the .net dll, but I still want them to go to my custom error page. Any thoughts?
Comment permalink 9 Milan Negovan |
With a non-existing folder the approach is pretty much the same as with pages---you need to configure IIS to redirect to the ASP.NET ISAPI. As to files with the extensions you listed, you can still map ASP.NET to serve them if you need to, and then they become subject to your custom error pages.
Comment permalink 10 Mauricio Quiros |
Great article, simple and clear and the results are so cool. One doubt I have is while debuggin this aproach I always get the same error (message) in the example output. I debug to figure it out what's the reason and I find out that the exact problem is in the Inner Exception. Within the Exception. So this is right? or Im doing something wrong, thanks.
Comment permalink 11 Milan Negovan |
Mauricio, it really depends on what kind of exceptions you catch. For example, HTTP exceptions are quite generic (and cryptic, at that) with the real, meaningful exceptions stored in the InnerException property.

Generally, though, you don't have to dig into the InnerException.
Comment permalink 12 Mauricio Quiros |
Thanks a lot for your fast answer. I'm still kind of confuse about this because no matter what Exception I throw(Like the example: throw new Exception ("Silly exception");) I always get the same error.

Message: Exception of type System.Web.HttpUnhandledException was thrown.

Probably I'm doing something bad, I'll review it all again, but I really want the details of what was the exception (Just can see it in the Inner...), and in my case using the "CustomErrors4 PRoject Example" I always get the same error message too.

That's it and again, Thanks a lot for your time to answer.
Comment permalink 13 Henrique |
Well fellows, i might have some aswers let me post this code:
when u want to raise a not founded code:
throw new HttpException(404,"File Not Founded");
and in the web.config
< error statusCode="401" redirect="/Denied.aspx" />

quite simple??
Comment permalink 14 chris mcbride |
this is all quite handy, and i'm using the OnError overload right now. It doesn't perform like I want it too, though...

When I trap the error in application_error, the page output is displayed. WHen I trap in OnError at the page level, the page output isn't shown (that is, the first way my header and footer are still in the output stream surrounding the error message. With OnError, I'm only getting a white page with my error message).

Is there any way to get the whole output stream with onError?
Comment permalink 15 Niktu |
Yup, I'm trying to resume page generation too (after catching with overload of OnError, or possily bit more elegant Page_Error tied to Error Event ...).
Comment permalink 16 atul |
This is the far the best article on handling error i have read...

Thanks
Comment permalink 17 Matt Jensen |
Nice article - thanks.
Just wondering, in the case where you're webserver runs htm, .asp and .aspx pages, is there a way to also map classic ASP pages to this error handling method? It would be good to be able to just use one method (e.g. web.config to handle all errors), rather than web.config for .aspx and .htm errors, and the IIS settings for classic ASP.
This may be a stupid question, but can you map classic asp pages to the asp.net isapi also? I presume you can't, but thought it vaguely possible that the .net isapi is 'backwards' compatible, as it were?
Thanks
Cheers
Matt
Comment permalink 18 Vishal Kaushik |
Very informative. nice done! Loved it.
Comment permalink 19 Milan Negovan |
Matt, you can map just about any extensions to the ASP.NET ISAPI. But remember: once you do that, you're responsible for serving those types of files. It opens a whole can of worms.
Comment permalink 20 Sean Smith |
This article really helped me fix the problem quickly. Thank you for an excellent, well laid-out resource.
Comment permalink 21 Dave |
This article is the best I've read on error handling in ASP.NET and has been a good learning guide. Is it possible however to provide a VB version instead of C# so I can attempt the more complicated stuff using httpModules??? Thanks!
Comment permalink 22 Erik |
When your not using .NET's custom errorpage, and your page has an error you will normaly receive a HTTP 500 error in your HTTP Header.

With Custom error turned on you first get a HTTP 302 header (redirect) and secondly - when error.aspx is get - a HTTP 200 header.

So IIS doesn't log any HTTP 500 (404 etc.) errors anymore,

This gives a wrong picture when using IIS log analysers. And search engines can't detect 404 anymore because eventually 200 is returned.

What can I do to correct this?
Comment permalink 23 Benjamin |
Clear and to the point. Thanks!
Comment permalink 24 Milan Negovan |
Erik: I think it would be enough to set HttpContext.Current.Response.StatusCode = 404 somewhere on the page.
Comment permalink 25 MousePad |
Useful!
Comment permalink 26 chirag |
Hi,
in C# & Asp.net
I have a error in config file(Configuration Error) so is ther any way tht i can catch the configuration error & display a particular message.
Comment permalink 27 Milan Negovan |
I don't think you can trap errors that occur in config files. I might be wrong, so if anyone knows, please leave a comment.
Comment permalink 28 Dave |
I have run into a problem with custom 404 erros. I developed a 404.aspx page with a Close button on. I use session variables to determine which page the user will returned to depending on the page they arrived at this erorr. I have a linkbutton with code behind to redirect to the proper page. Everything renders fine except this link button. It doesn't center the link nor does it display as a link, just shows the text 'Close'

< asp:table runat="server" id="tblClick">
< asp:TableRow HorizontalAlign="center">
< asp:TableCell>
< asp:LinkButton ID="lkbClose" runat="server" OnClick="Close_Click">Close
< /asp:TableCell>
< /asp:TableRow>
< /asp:table>

Code behind:

public void Close_Click(object sender, EventArgs e)
{
Response.Redirect(Session["Pagepath"].ToString() + Session["PageName"].ToString() + "?qstrKey=" + Session["iKey"].ToString());
}

Web config:

< customErrors defaultRedirect="~/Error/GenericError.aspx" mode="On">
< error statusCode="404" redirect="~/Error/404.aspx" />



For now I just have the user click the browser back button but I really don't like that solution.

Any assistance would be greatly appreciated -
If you could please respond via e-mail
Dave
Comment permalink 29 Leblanc Meneses |
jkgreer great link!

i normally use exception handlers to log to db
then forward user to error.php?code=unhandledexception
error.php?code=404
Comment permalink 30 Udi |
I get all aspx errors reported, but if I mistakenly forget to upload for example a .cs page to the production server,
the clients get an error page, but I don't get a report on such scenarios.

I guess such an error is on compilation on the production server itself and the HTTPHandler is not getting them.

Is there a solution for this kind of problem?
Comment permalink 31 Milan Negovan |
I don't know if it's possible to trap errors this early in the page life cycle with the technique I described in the article. I believe the problem is that the HTTP pipeline is not available yet, so you need some other, low-level way of detecting errors.
Comment permalink 32 Migel Ángel |
Hi everybody:
I have found this code very interesting if you want to capture only the error 40*, for example, the 404, as you know, when you use a module or the global.asax to get the unhandled errors, you capture the 404 errors too, so with these lines of codes you can react:

System.Exception appException = Server.GetLastError();

if (appException is HttpException)
{
HttpException checkException = (HttpException)appException;
switch (checkException.GetHttpCode())
{
case 403:
{
errMessage.Append("You are not allowed to view that page.");
break;
}
case 404:
{
errMessage.Append("The page you requested cannot be found.");
break;
}
}

Saludos,
Dactivo
http://www.d-activo.com
Comment permalink 33 Adi |
Milan, Udi,

Yes, there is. You can handle such an exception in Application_Error. I did not reproduced Udi's case, but let's have a quick test. Taking this same URL we're on now, insert the character | anywhere in between the domain and the aspx extension. You'll get an exception that can be handled in your Application class. The compilation would happen after getting the path to the resource so, if you can handle the first (invalid path), you can handle the second.

If anyone did tested, please comment.
Comment permalink 34 Swetha |
Nice article. Do expect more.
Thanks
Swetha
Comment permalink 35 Mark Petersen |
What about using IIS to handle the different HTML error codes? In IIS, go to the Properties of a website, click the Custom Errors tab. For each Html error, you can specify a message type of Url, which you could point to an aspx page that would get the last error and display accordingly.

I'm not entirely sure whether IIS does a full redirect (where you lose the ability to get the last error) or not.
Comment permalink 36 Ashok |
Can we get entire response stream with forms, controls with value when the error occured? So that we can easily diagnosis the error.
Comment permalink 37 Hunt |
Eric,
I've seen this...
<%
Response.Status = "404 Not Found"
%>

Put the above in your 404.html page to keep Google and others happy

Above has not been tested.
Comment permalink 38 Bryan Siebuhr |
Is anyone successfully using this approach to trap exceptions related to file uploads that exceed maxRequestLength? Does this approach break down when the request is too big?

I have been able to catch the exception in global.asax using the Application_OnError event. I can extract the exception codes and messages just fine and see them in my Watch windows in VS, and I can execute the Server.ClearError(). However, when I try to display the codes and messages using Response.Write or I try a Response.Redirect to another page all I get is the generic "can't display the page" error display.

Any ideas would be appreciated
Comment permalink 39 huzz |
Thanks for the brilliant article..
Comment permalink 40 Duc Bui |
Good article from which I've learnt a lot. Thanks everyone!!!
Comment permalink 41 Matt |
Nice example. Very worthwhile.

-M
Comment permalink 42 Abhilash |
This was really useful.

Thanks
Comment permalink 43 Robin |
Nice article. Explained the details beautifully!
Thanks!
Comment permalink 44 Mark Kamoski |
When I call GetLastError() on the page that is set as the defaultRedirect in web.config that call always returns null?
Comment permalink 45 venkatesh |
Great Article. I have a small query.
I have a website (ASP.NET 2.0+C#+SQL Server 2000) published on the test server. The server's disk space runs out and so the website is no longer viewable to the user. I would like to provide a custom message to the user, if the server space is low.

How to provide the customized message to the user, incase the disk space runs out?
Comment permalink 46 Milan Negovan |
Venkatesh, you can have an HttpModule check for disk space on every page request, or you can have a superclass for all your pages to derive from where you can conduct this check.
Comment permalink 47 James Devlin |
Good post, I've included it in my Custom ASP.NET 404 Error Page Manifesto.

Just in case that links doesn't turn out properly (no BBCode?):

http://www.codingthewheel.com/archives/custom-asp-net-404-error-page-manifesto
Comment permalink 48 James Devlin |
By the way, that's a work in progress. :-)
Comment permalink 49 mike carn |
Very clear and concise article with plenty or references and source code example. Doesn't get any better than this unless it was written in VB.net :) thanks.
Comment permalink 50 kiso |
nice one
Comment permalink 51 Tobias |
Apart from using goto's the article is ok.
Comment permalink 52 Sergey |
Great article . Thank you
Comment permalink 53 Asif |
Best Asp.net error handling article !
Comment permalink 54 Parimanam |
very useful article in error handling in asp.net
Thans Milan

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):