Recently, while going through the Exception handling and logging, I found an interesting topic which I would like to share – “Exceptions“, which is a family member to every language/technology used. These are sometimes irritating for the developers. If it’s irritating for developers, what would be the condition of the end user when he/she views the “yellow screen populated with God knows what!“.
Now the question arises, should they be displayed with that entire stack trace that is sometimes helpful for developers to resolve errors? The answer obviously is “NO”.
Here is a small tip that might be handy. Here, I am trying to detail the Use of “Custom Errors“and its attributesand elements. Web.config, the main settings and configuration for an ASP.NET web application, is the file where the custom errors find its existence.
According to MSDN, custom errors elements provide information about custom error messages. The main motive here is to display the end user custom error pages. First, let’s know how the custom errors are written in the web.config (as we know in XML format):
<customerrors mode="On">
Another attribute that is used is “defaultRedirect
“. This is an optional attribute that is used to redirect the browser to the default error page if any, else generic errors are shown to the users.
<customerrors defaultredirect="Error/Index" mode="">
customErrors
. The one which I have used and came across is the error element. This might be handy if there is a requirement to show specific error pages for specific HttpStatusCodes(401,404,500)
.<customerrors defaultredirect="" mode=""> <error statuscode="400" redirect="NotFound.htm"> <error statuscode="500" redirect="InternalServerError.htm">
Another important thing to note is Custom Errors can be defined in two levels:
customErrros
described above &the
Page directive, i.e., for specific pages. Use of “ErrorPage
” attribute is done here.We also handle exceptions in Global.asax, i.e. using:
protected void Application_Error(Object sender, EventArgs e) { Exception ex = Server.GetLastError(); //self explanatory gets the most recent error Server.ClearError(); //self explanatory clears the error //(Required to clear as otherwise user gets to see the default ASP.NET error handlers) Response.Redirect(""); //default redirect. }
Now the precedence, that is:
Quote:
When all are defined, then Page level will have higher precedence that global.asax and
customErrors
. And if thecustomErrors
are also defined along with in Global.asax, thencustomErrors
will have no effect and if no exception handling is done in the global.asax, then Web.config that iscustomErrors
come into action.
customErrors
in Web.config.Server.GetLastError()
returns null
.protected void Application_Error(Object sender, EventArgs e) { Response.Redirect("HandleException.htm"); //default redirect. }
null
.Here, I end this. Thanks for reading. Hope you learnt something from this.
References:
DotNet Tricks
]]>