I need to handle 404 exceptions differently than all other types of them. What is the best way to identify those 404 exceptions (distinguish them from other exceptions)?
The problem is that there is no a special exception class for 404 errors, I get regular System.Web.HttpException with Message = "File does not exist."
Should I just use exception's message for it or is there a better way?
Thank you.
Best web development and SEO practices dictate that any webpage which does not exist, return an HTTP response code of 404, or Not Found. Basically, this response code means that the URL that you're requesting does not exist.
Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception. If the application does not handle the exception, the browser is forced to display the error details.
The following are some common causes of this error message: The requested file has been renamed. The requested file has been moved to another location and/or deleted. The requested file is temporarily unavailable due to maintenance, upgrades, or other unknown causes.
You can try to cast the exception as an HttpException
, and then use the GetHttpCode
method to check whether it is a 404 or not.
For example:
Exception ex = Server.GetLastError();
HttpException httpEx = ex as HttpException;
if (httpEx != null && httpEx.GetHttpCode() == 404)
{
//do what you want for 404 errors
}
I'd suggest that you configure your application to redirect 404 errors to a specific page, such as ~/FourOhFour.aspx
. In this page you can inspect the aspxerrorpath
querystring parameter, which will report the page the user was attempting to visit. From here you can do all sorts of interesting things, from logging the 404, to emailing yourself a message, to trying to determine the correct URL and auto-redirecting the user to that.
To configure your web application to redirect the user to a custom page in the face of a 404, add the following markup to web.config
in the <system.web>
section:
<customErrors mode="On" defaultRedirect="~/GeneralError.aspx">
<error statusCode="404" redirect="~/FourOhFour.aspx" />
</customErrors>
For more information, see:
<customErrors>
element documentationIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With