Custom Error Page In ASP.NET

In this article, we will learn how we can manage the user screen of our website when runtime error occurs.
 
By default, Visual studio throws an ugly "yellow screen of death (YSOD)" at the time of runtime errors. We can manage it by applications <customErrors> configuration.
 
 
This yellow screen of death show what kind of error is this, also shows details of exception which is quite useful from the point of developers, by which they can go through that error details and debug their application accordingly but from the end user's point of view this YSOD is nasty.

At this moment developer can handle how users are shown a better error page by configuring <customError> in web.config page. There are couple of attributes we need to set.

We need to provide the following attribute value:
  • defaultRedirect
  • mode
  1. <configuration>  
  2. <system.web>  
  3. <compilation debug="true" targetFramework="4.5" />  
  4. <httpRuntime targetFramework="4.5" />  
  5. <customErrors mode="" defaultRedirect=""></customErrors>  
  6. </system.web>  
  7. </configuration>  
DefaultRedirect

Here we pass the URL of custom error page.If we want to redirect to our custom error page instead to that annoying Yellow Screen Of Death(YSOD).
This is optional attribute.

Mode

There are 3 mode depending upon where the user visited that screen locally or remotely.
  • on
  • off
  • RemoteOnly


On

Custom error page or runtime yellow screen of death is shown to local as well as remote user.

Off

Exception details YSOD are shown to local as well as remote user when exception occurs.

RemoteOnly

Custom error or yuntime errors YSOD is shown to all the users (visitors) whether they are local or remote.

Steps for Custom Error Page

Create a separate folder for Error.Add Web Form for custom error page.



Set <customErrors> setting in Web.Config file of the application.

Pass defaultRedirect and mode attributes in <customErrors>.
  1. <configuration>  
  2. <system.web>  
  3. <compilation debug="true" targetFramework="4.5" />  
  4. <httpRuntime targetFramework="4.5" />  
  5. <customErrors mode="" defaultRedirect=""></customErrors>  
  6. </system.web>  
  7. </configuration>  
If you want to set your application level exception should redirect to your custom error page, you can do this by going to global.asax file and write the code for redirection in Application_Error method.

For handling all the exception, you just need to write the code for redirection at catch section. Also you can set custom error page for http errors by passing statusSode.
  1. <customErrors mode="RemoteOnly" defaultRedirect="~/ErrorPages/Oops.aspx">  
  2. <error statusCode="404" redirect="~/ErrorPages/404.aspx" />  
  3. </customErrors>  
Closure:

In this section we learned how to customize our error screen.
 
Happy Learning ! 

Up Next
    Ebook Download
    View all
    Learn
    View all