Search Sreeni's Insights

Filter by content type
cloud November 28, 2017 6 min read

How to set up Sentry for .NET and JavaScript error tracking?

Sentry brings API and browser exceptions together with release and environment context, helping teams compare SaaS and on-premise tracking and improve error response.

Share:

How to set up Sentry for .NET and JavaScript error tracking?

An exception which is reaching production without useful context is becoming a support call. The server log may show a stack trace, while the browser failure is only showing a blank page. When the API and JavaScript application are using separate error tracking approaches, an operator is joining information by hand.

In this article, we are going to see how to set up Sentry SaaS or an on-premise Sentry service for a .NET application and JavaScript client. The .NET example uses SharpRaven, the browser example uses raven-js, and we will also configure environments, releases, source maps and alerts without sending PII.

TL;DR Summary

  • Sentry collects exceptions and context in one error-tracking service.
  • Use SharpRaven for the .NET application and raven-js for the JavaScript application.
  • Capture exceptions in ASP.NET Core middleware or an MVC filter, then rethrow or return the correct response.
  • Configure a DSN, environment and release so an error can be grouped and traced.
  • Upload source maps for readable JavaScript stack traces.
  • Do not send passwords, tokens or unnecessary personal data as user context.

Challenges

Server and browser blind spots

An API can fail while the browser is showing only a generic error. A JavaScript exception can fail before an API request reaches the server. Without one searchable event system, the support team is discovering only part of the customer journey.

Too much exception noise

Not every exception is a new incident. Retries, validation errors and browser extensions can create repeated events. Grouping, release and environment values are helping us distinguish a deployment regression from a known handled condition.

Source maps and privacy

Minified JavaScript is difficult to read in an error report. Source maps improve the stack trace, but uploading them and sending user context must be controlled so source code and personal data are not exposed unexpectedly.

What is Sentry?

Sentry is an error tracking service which receives exceptions, stack traces, context and release information, then groups and displays them for investigation.

In simple terms, Sentry is a searchable front door for application errors. It is not replacing application logs, health checks or an incident process, but it is reducing the time needed to find a failing code path.

The following diagram depicts the .NET and JavaScript applications sending errors to Sentry.

Sentry error event flow
Sentry error event flow

The purple path is an exception from the API or browser being captured, enriched with release and environment context, and delivered to the Sentry service.

Why Sentry is important?

Sentry is important because it is joining stack traces, release information and error frequency in one place. We can see whether a problem started after a release and whether it is affecting the API, browser or both.

Choose Sentry SaaS when the team accepts a hosted service and its data location. Choose an on-premise installation when operational control and data residency require it. We will see how to scale Sentry with ACI in an upcoming article.

For a fund application, keep the release value identical between the API and browser build when they are released together. When they are deployed separately, use separate release values and link the deployment records, so an operator can still understand which client and server versions were involved.

Option comparison

ApproachProsCons
Sentry SaaS+ Fast setup
+ Hosted search and alerting
− Event data is sent to the service
− Subscription and retention decisions
Sentry on-premise+ More control over data and network
+ Internal retention policy
− Team operates storage and upgrades
− More infrastructure

Steps to Implement:

Follow the following instructions to set up error tracking,

Create the Sentry project

  • Create separate projects or environments for the API and JavaScript application.
  • Record the DSN and project name.
  • Set the release name from the build output, for example <application-name>@<release>.

Replace the input place holders with actual values. Do not paste a real DSN with private credentials into source control; use the project configuration process.

Install SharpRaven

  • Add the .NET package,

    Install-Package SharpRaven
  • Create a Raven client,

    using SharpRaven;
    using SharpRaven.Data;
    
    var ravenClient = new RavenClient("<dsn>");
    ravenClient.Capture(new SentryEvent(exception));
  • Keep the client as an application service rather than constructing it inside every catch block.

The DSN is an input placeholder and should be configured by environment. Do not log the DSN together with access or user information.

Capture ASP.NET Core exceptions

  • Add middleware around the application pipeline,

    public class SentryExceptionMiddleware
    {
        private readonly RequestDelegate next;
        private readonly RavenClient ravenClient;
    
        public SentryExceptionMiddleware(
            RequestDelegate next,
            RavenClient ravenClient)
        {
            this.next = next;
            this.ravenClient = ravenClient;
        }
    
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception exception)
            {
                ravenClient.Capture(new SentryEvent(exception));
                throw;
            }
        }
    }
  • Register the middleware after the error-handling decision required by the application.

  • Add request, release and environment context without adding secret values.

Rethrowing lets the normal ASP.NET Core error handling and status code process continue. If a filter handles an exception and returns a response, capture it once and avoid a second duplicate event.

Add raven-js

  • Install raven-js from the approved JavaScript dependency source.

  • Configure it at application startup,

    Raven.config('<public dsn>', {
        environment: '<environment>',
        release: '<release>'
    }).install();
  • Capture an exception,

    try {
        renderFundPrice();
    } catch (error) {
        Raven.captureException(error);
    }
  • Add user context only when the value is approved,

    Raven.setUserContext({
        id: '<internal-user-id>'
    });

Do not put an email address, name or account data into user context unless the privacy review allows it. Replace the input place holders with actual values through the build configuration.

Upload source maps and releases

  • Generate source maps during the JavaScript build.

  • Upload them with the Sentry CLI,

    sentry-cli releases -o <organization> -p <project> new <release>
    sentry-cli releases -o <organization> -p <project> files <release> upload-sourcemaps <source-map-folder>
    sentry-cli releases -o <organization> -p <project> finalize <release>
  • Confirm that the release value in the browser event exactly matches the uploaded release.

Keep the authentication token for the CLI in a protected build variable. Do not put it in the JavaScript bundle.

Configure alerts and pulse check

  • Create an alert for a new error event or an increase in event frequency.
  • Filter by environment so development errors do not page production support.
  • Deploy a controlled test exception in a non-production environment.
  • Confirm grouping, release, stack trace and source-map display.
  • Confirm the API event and browser event are both searchable.

Note: Sentry is one part of the operational pipeline. Keep the structured application logs and health checks described in the other Coding Practices posts.

Must Do / Should / Don’t

Must Do

  • Must configure environment and release on every event source.
  • Must capture unhandled server exceptions without changing the response contract.
  • Must upload source maps through a protected build process.
  • Must remove secrets and unnecessary PII from event context.

Should

  • Should use separate environments for development, UAT and production.
  • Should configure alerts for new regressions and sustained error rates.
  • Should group known validation failures away from actionable incidents.

Don’t

  • Don’t send passwords, tokens, request bodies or unnecessary personal data.
  • Don’t expose the Sentry CLI token in a browser bundle.
  • Don’t create duplicate events by capturing and rethrowing through multiple handlers.

Wrap up

In this article, we have looked at Sentry SaaS and on-premise options, SharpRaven, raven-js, ASP.NET Core exception capture, source maps, releases, environments and alerts.

Thanks for reading this article. In the next article, I will walk you through how to configure Azure API Management policies for rate limiting and caching.

Related Posts