Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Error Monitoring in ASP.NET MVC

DZone's Guide to

Error Monitoring in ASP.NET MVC

In this post, we'll look at how to catch errors and exceptions in ASP.NET MVC using a global action filter, and how to track them with a great error monitoring tool.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

ASP.NET MVC is a modern web development framework that combines the features of MVC (Model-View-Controller) architecture for better separation of concerns and the best parts of the ASP.NET platform.

We'll show you an example of how to catch errors and exceptions in ASP.NET MVC using a global action filter. We'll also show you how to track them in Rollbar's error monitoring service. This will give you real-time visibility into your errors in production. It also captures person data and other contexts from your app so you can solve errors faster.

Above, you can see that we've created an example app that triggers an exception when the user clicks on a button. The error message is tracked in Rollbar, including a stack trace where you can see the line of code that caused the error.

Create a Global Action Filter

To track all of our exceptions, we have multiple approaches in .NET. Using a global action filter is the easiest way to catch all the exceptions. It receives uncaught exceptions for your whole application, not just an individual controller. We'll show you how to override it to create your own global action filter with exception tracking. Here are some simple steps to create a global action filter in your application.

  1. Open up your own ASP.NET MVC project or use our open source example on GitHub at Rollbar-Dotnet-Example. You can use this filter to add any error monitoring solution, but we will show an example of how to set up Rollbar in the next section.
  2. Next, let's create our own exception filter to catch exceptions. In your App_Start folder, and add a .cs file by extending IExceptionFilter. You need to override the OnException method, allowing you to catch the exception that is going to occur throughout the project. You can find the App_Start folder inside your application directory.
  3. namespace RollBar.App_Start
    {
     public class RollbarExceptionFilter : IExceptionFilter
     {
       public void OnException(ExceptionContext filterContext)
       {
         if (filterContext.ExceptionHandled)
         return;
       }
     }
    }
  4. Now we need to add a FilterConfig to add our custom filter to the GlobalFilterCollection. You can find the FilterConfig.cs file inside the App_Start folder.
  5. namespace RollBar
    {
     public class FilterConfig
     {
       public static void RegisterGlobalFilters(GlobalFilterCollection filters)
       {
         filters.Add(new RollbarExceptionFilter());
       }
     }
    }
  6. Finally, register it in the GlobalFilters in the Application_Start method. You can find the Application_Start method in Global.asax, which is in the root application directory.
protected void Application_Start()
{
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

Add Rollbar Error Monitoring

Now that we have our global action filter wired up, we're going to show you how to integrate Rollbar's .NET SDK into your code.

  1. Visit https://rollbar.com and sign up for an account if you haven't yet. Next, create your project and select .NET from the list of SDKs. Save the server side access token that is generated for you. You'll need this to configure Rollbar in the steps below.
  2. Install the Rollbar using NuGet Package Manager. You can install Rollbar using the Package Manager Console or in Manage NuGet Package for Solution. You can find both options in Visual Studio under Tools->NuGet Package Manager. Alternatively, to install from the console, run the command below:
  3. Install-Package Rollbar
  4. Configure the Rollbar SDK with the access token you received earlier. Add it to the Global.asax file and inside the Application_Start method.
  5. protected void Application_Start()
    {
     const string postServerItemAccessToken = "Your Post Server Access Token";
    
     RollbarLocator.RollbarInstance.
     Configure(new RollbarConfig(postServerItemAccessToken)
     {
       Environment = "production"
     });
    }
  6. Now add the Rollbar error tracking inside the global action filter we created earlier. Add it to the OnException method to send the crash log to Rollbar.
  7. RollbarLocator.RollbarInstance.Error(filterContext.Exception);

You can also use Rollbar to track caught exceptions and other items using the same Rollbar instance. Learn more about the full API in our .NET documentation.

Test With an Example App

To test that it’s working, let's create a page that will generate an error message. In the example below, you’ll be able to generate an error by clicking the "Throw an error" button.

First, we’ll create a new form with a button to call the CreateErrorController action on the server.

@using (Html.BeginForm("GenerateError", "CreateError", FormMethod.Post))
{
  <input style="height:50px;width:200px" type="submit" value="Generate an error"   name="name" />
}

When you click the "Generate an error" button, it will trigger the GenerateErrormethod. In this method, we have added a bug which is throwing an exception with the text, “This is test exception.”

namespace RollbarDotnetExample.Controllers
{
  public class CreateErrorController : Controller
  {
    // GET: CreateError
    public ActionResult Index()
    {
      return View();
    }

    [HttpPost]
    public ActionResult GenerateError()
    {
      throw new Exception("This is test exception.");
    }
  }
}

Since we wired up our global action filter to report the error to Rollbar, we should see the error show up on Rollbar’s item page. Below, you can see that this error last occurred 2 minutes ago.

Screenshot of Rollbar .NET MVC Dashbord

The item page shows us a full stack trace including the line number where the error occurred. Using the tabs above the trackback, you can see more contextual data to help determine the cause of the problem. For example, you can get extra information on which people were affected, which browsers they were using, which IP address they have and more.

Screenshot of Rollbar .NET Error Detail

Now you know how to catch exceptions in ASP.NET MVC applications! You also saw how easy it is to set up Rollbar for error monitoring. Learn more in our documentation for .NET, and sign up for a free trial today!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,error monitoring ,asp.net mvc

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}