Click here to Skip to main content
15,878,748 members
Articles / Web Development / ASP.NET

ASP.NET Health Monitor and Custom Errors

Rate me:
Please Sign up or sign in to vote.
3.75/5 (7 votes)
22 Feb 2012CPOL3 min read 22.1K   10   4
Enable email notifications on errors, and create custom pages for handling errors in MVC

Monitoring is an important part of the project life, ASP.NET provides features that make it easy to monitor your web app while it is in production, it is called ASP.NET Health Monitoring.

Enabling Health Monitor

Create a new ASP.NET MVC 3 Web Application and edit the Web.Config file, add the following between the <system.web> tags:

XML
<!-- Health Monitoring -->
  <healthMonitoring enabled="true">
    <providers>
      <clear />
      <!-- Email WebEvents Provider -->
      <add name="EmailWebEventProvider"
  type="System.Web.Management.SimpleMailWebEventProvider"
  from="logger@mydomain.com" to=MY_USERNAME@gmail.com
  bodyHeader="My Monitor" buffer="false" />
    </providers>
    <eventMappings>
      <clear />
      <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
      startEventCode="0" endEventCode="2147483647" />
    </eventMappings>
    <rules>
      <clear />
      <add name="All Errors Default" eventName="All Errors"
  provider="EmailWebEventProvider" profile="Default" minInstances="1"
  maxLimit="1000" minInterval="23:59:00" />
    </rules>
  </healthMonitoring>

Here we have enabled health monitoring with an Email Alert for any error that occurs but we will only be notified once a day for each specific error, as we have set minInterval=”23:59:00?.

To complete the configuration, go ahead and set the “from”, “to”, and “header” properties in the above code, for more details on the health monitor properties, go here.

GMAIL SMTP Server

At this point, it will use the default local host smtp server, if you don't have an SMTP server running, you can set it up to connect to any available server, here we are using gmail SMTP server as I have a gmail account (500 email/day limit).

Add the following after the <system.web> tags:

XML
<!--SMTP -->
  <system.net>
    <mailSettings>
      <smtp from="noreply@mydomain.com" deliveryMethod="Network">
        <network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" 
    password="MY_PASSWORD" port="587" userName="MY_USERNAME@gmail.com" />
      </smtp>
    </mailSettings>
  </system.net>

Enter your email and password in the “password” and “userName” fields.

ERROR DEMO

To trigger an error, we will add the following code to the “HomeController”:

VB.NET
Function Index() As ActionResult
ViewData("Message") = "Welcome to ASP.NET MVC!"

Throw New ArgumentException("ERROR FROM HomeController")

Return View()
End Function

Open the site and you will get an error, and an email notification.

Handling Errors

To suppress these errors and show our own custom page, we have to do some extra work, in our global.asax file, we add a global error handler, then we create views for each of the different types of errors you want to have a custom page for.

Open Global.asax and add the following code:

VB.NET
Private Sub MvcApplication_Error(sender As Object, e As System.EventArgs) _
    Handles Me.Error
Dim routeData = New RouteData
routeData.Values.Add("controller", "Home")
Dim lastEx = Server.GetLastError
If TypeOf (lastEx) Is HttpException Then
Dim ex As HttpException = lastEx
Select Case ex.GetHttpCode
Case 404
routeData.Values.Add("action", "Error404")
Case 500
routeData.Values.Add("action", "Error500")
Case Else
routeData.Values.Add("action", "ErrorGeneric")
End Select
Else 'not an Http Ex.
routeData.Values.Add("action", "ErrorGeneric")
End If
routeData.Values.Add("exception", lastEx)
Server.ClearError()
Dim errController As IController = New ErrorController
errController.Execute(New RequestContext(New HttpContextWrapper(Context), routeData))
End Sub

In the above code, we handle the Me.Error global event, then we choose which view we want to show based on the HttpCode, and Exception type, we also put our Exception in routeData (optional) so it will be available to us in our View, clear the error that tells ASP.NET that we handled it, and then return one of the Views from the ErrorController. Let’s create the ErrorController.

ErrorController

Create a new controller, name it “ErrorController”, and add the following code:

VB.NET
Public Function Error404() As ActionResult
Response.StatusCode = 404
Dim ex As Exception = Nothing
If RouteData.Values.ContainsKey("exception") Then
ex = RouteData.Values("exception")
End If
Return View(ex)
End Function
Public Function Error500() As ActionResult
Response.StatusCode = 500
Dim ex As Exception = Nothing
If RouteData.Values.ContainsKey("exception") Then
ex = RouteData.Values("exception")
End If
Return View(ex)
End Function
Public Function ErrorGeneric() As ActionResult
Dim ex As Exception = Nothing
If RouteData.Values.ContainsKey("exception") Then
ex = RouteData.Values("exception")
End If
Return View(ex)
End Function

Here we have 3 views, one for 404 (Not Found), another for 500 server error, and a default generic error handler. We inspect if we passed in the exception in routeData and pass it to our view as the view model type.

Right click on the “Shared” folder and create the following 3 views.

Error404.vbhtml

@ModelType Exception
@Code

ViewData("Title") = "Error 404 : Page not found"

End Code
@ViewData("Title")
My Custom Error Page

@Model.Message

@Model.StackTrace

Error500.vbhtml

Save as above.

ErrorGeneric.vbhtml

Save as above.

Now if we rebuild and open the site again, we will see the following screen:

Screenshot

At this point, your site has been setup to email you when errors occur in your app, and if they do, the visitor will see a nice custom error page. With this in your app, you can handle more complex scenarios like having a 404 page that inspects the Exception passed in and tries to figure out what the visitor was trying to find in our site and give them some suggestions.

You can download the full sample project here.

I hope you like this post and for my next post, I will be looking at creating a whole site using ASP.NET localization features.


Filed under: .NET, ASP.NET, MVC, VB.NET

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) KUFPEC
Kuwait Kuwait
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestioncustomErrors , httpErrors , healthMonitoring Pin
kiquenet.com2-Nov-15 1:01
professionalkiquenet.com2-Nov-15 1:01 
Questionasp.net 4.5 webforms and performance Pin
kiquenet.com2-Nov-15 0:54
professionalkiquenet.com2-Nov-15 0:54 
Question[My vote of 1] C# is needed here Pin
msdevtech18-Feb-13 5:02
msdevtech18-Feb-13 5:02 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey19-Mar-12 19:34
professionalManoj Kumar Choubey19-Mar-12 19:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.