Make Angular’s source code available to Sentry with GitLab CI
Tags: angular, gitlab, typescript, sentry
Published: 2019-10-28 15:31:38

---
title: Make Angular’s source code available to Sentry with GitLab CI
published: true
date: 2019-02-18 08:03:42 UTC
tags: angular,gitlab,typescript,sentry
canonical_url: https://medium.com/angular-athens/make-angulars-source-code-available-to-sentry-with-gitlab-ci-b3020bd60ae6
---

![](https://cdn-images-1.medium.com/max/1024/1*3I5cszV_0FUDtgaO_Z1oIA.jpeg)<figcaption>Source: <a href="https://pixabay.com/en/gummib%C3%A4rchen-fruit-gums-bear-359950/">pixabay.com</a></figcaption>

At [COVIS](https://twitter.com/COVIS_GmbH) we have been using [GitLab](https://about.gitlab.com/), [Sentry](https://sentry.io/welcome/) and [Angular](https://angular.io/) for a while now. Until recently, it was not very straightforward to build the necessary source map files for an Angular application and make them available to Sentry. Without the source map files, the stack trace of the exception is not very useful.

In this post we will see how to:

1. Integrate Sentry with GitLab
2. Setup GitLab CI pipelines that deploys an Angular app to GitLab pages
3. Extend our pipeline to build source maps files and upload them to Sentry

**Note** : This is my first post so be gentle and I am looking forward to your feedback 😊. We will be using the SaaS version of Sentry for this post. You will have to create accounts both on GitLab and Sentry (free tiers will do just fine).

### Introduction

It is hard to image writing an application these days without git. [GitLab](https://about.gitlab.com/) is a full DevOps tool that can serve as source code repository, continuous integration and continuous delivery tool. GitLab became very popular last year with the [#movetogitlab](https://about.gitlab.com/2018/06/03/movingtogitlab/)thing (btw I love GitHub too).

[Sentry](https://sentry.io/welcome/) is a tool that can help after our applications are on production. It provides a rich [set of features](https://sentry.io/features/) for collecting, identifying and understanding what may have gone wrong.

But Angular application are written in TypeScript and our source code gets compiled, minified, uglified and now it is so much harder to understand our logged exception stack traces and figure out what when wrong!

In this post we will see how we can create a build process that enables us to see our original TypeScript source code logged in the exception stack trace in Sentry.

### Integrate Sentry with GitLab

We will start by creating a new GitLab group and repository. Then we will create our Sentry project and enable the integration between our Sentry project and our GitLab repository.

On GitLab, from the top menu, click **Groups** , and click the green button **New group**. We will name our group _“angular-sentry-demo”_

Once the group is created, click the green button **New Project**. We will name our project _“demo-ng-app”_

![](https://cdn-images-1.medium.com/max/1024/1*4P2a1aO2rmJRzd-PUcOLZg.png)<figcaption>Create GitLab project</figcaption>

Now let’s create a new Sentry project. Navigate to [https://sentry.io/signup](https://sentry.io/signup/) and create an Account if you do not have one already. Once you have your account click on the _“Create project”_ button. We will name our project _“demo-gitlab-ng” and select the Angular SDK:_

![](https://cdn-images-1.medium.com/max/699/1*s7IBK7zqIdZhB3Uy650iaw.png)

![](https://cdn-images-1.medium.com/max/1024/1*S4pg8KfUDRalTvZ1ZW2DOA.png)<figcaption>dempSentry project creation</figcaption>

Once your project is ready, the quick-start sample code will be presented to you showing your project’s DSN. The DSN is the most important thing as it tells the SDK where to send events. You can always find your project’s DSN in the “Client Keys” section of your “Project Settings” in Sentry. We will use the DSN later on when we configure the SDK.

Great! Now let’s perform the integration with GitLab. Please follow the steps 1–9 from the Sentry manual here:

[GitLab](https://docs.sentry.io/workflow/integrations/global-integrations/gitlab/)

👍 We have successfully integrated GitLab and Sentry! Now let’s move on to create our sample Angular application.

### Setup GitLab CI pipelines that deploys an Angular app to GitLab pages

We will now create a new Angular app and install the Sentry SDK. This will allow us to capture exceptions from our application, but on the generated code. On the final section we will change that.

#### Create new Angular app

We will create our application using the ng new command of the [Angular CLI](https://cli.angular.io/):

```
ng new demo-ng-app
cd demo-ng-app
```

Then we will add our generated application to our GitLab repository:

```
git remote add origin git@gitlab.com:angular-sentry-demo/demo-ng-app.git
git push -u origin master
```

#### Add Sentry SDK to Angular

Let’s install the Sentry SDK on our newly created application. We will follow the instructions

```
npm i -S [@sentry/browser](http://twitter.com/sentry/browser)
```

Now we will configure the SDK as documented on the Sentry documentation here:

[Angular](https://docs.sentry.io/platforms/javascript/angular/)

**Note** : Sentry documentation is smart enough to provide you the snippet with your own DSN.

That’s it! Now any unhandled exceptions will be sent to Sentry! But how did this happen? The snippet above implements Angular’s ErrorHandler class, that provides a hook for centralized exception handling. In the handleError method, the exception is send to Sentry using the captureException() method, before we rethrow it. If you want more info on these please check the following two links:

- [Angular](https://angular.io/api/core/ErrorHandler)
- [Capturing Events](https://docs.sentry.io/error-reporting/capturing/?platform=browser#capturing-errors--exceptions)

It is now time to send out first exception to Sentry. We will implement a simple button that raise an exception:

{% gist https://gist.github.com/loremaps/9c33cf3ecaa963672c69053c18b7485f %}

Now if we click the button, we will see the following exception stack trace logged under our Sentry project:

![](https://cdn-images-1.medium.com/max/1024/1*EOXxTLOQf7_QNkKijqOX0Q.png)<figcaption>Stack trace without source maps</figcaption>

Although we do get a lot of useful insights here, we do not see our source code. Let’s see if we can do better.

### Build Source Map Files

As you may know, Angular CLI uses [webpack](https://webpack.js.org/) under the hoods for several tasks of our application build process, including building our TypeScript code. Webpack is able to generate the source map files which will allow us to reference the original TypeScript code with the generated JavaScript. But configuring webpack is not an easy task and the Angular team wants to keep this abstracted from the developers. The ng eject command of the Angular CLI would reveal us the underlying webpack configuration and allow us to configure the source map file generation, but now there is a better way!

Recently, thanks to [**@** AlanAgius4](https://twitter.com/AlanAgius4) contribution 👏, we have better control over the source map files generation using Angular CLI **angular.json** file. The purpose of this file is to provide workspace-wide and project-specific configuration defaults for build and development tools. You can read more about it here:

[Angular](https://angular.io/guide/workspace-config)

We want to configure our angular.json file so that it generates the **hidden** source map files. They are called hidden, because the generated output files do not have references to them as opposed to the regular ones. This allows us to put them on Sentry without the need to host them on our web server. If you want to get deeper into source map files you can start here:

[Use a source map](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map)

So let’s configure our **angular.json** file to generate the hidden source map files during the production build:

{% gist https://gist.github.com/loremaps/640170b81ac5b26393abfcb97ef6ccc4 %}

Now when we build our application with ng build --prod, the source map files will be available under dist folder:

![](https://cdn-images-1.medium.com/max/373/1*SMi_RdEV-iV8srTCqZ9N0g.png)<figcaption>Generate</figcaption>

### Release Management

Sentry provides an abstraction called **Releases** which allow us to attach source artifacts to. The release API allows us to store source files (and source maps) within Sentry. In order to configure the release management, we need to do two things:

1. Configure the SDK with the release property during initialization e.g.:

```
Sentry.init({
 release: "my-project-name@2.3.12"
})
```

2. Use the release API to create the release, upload our artifacts and finalize it. We will see how to do this in the next section.

Since we are aiming to build a continuous integration pipeline, that builds our application with every commit on GitLab, we want to name our releases with something unique. The commit SHA is a good candidate for our release name. In order to do that, we need to be able to provide it as environmental variable. So we will start with adding a variable into our environment.ts and environment.prod.ts files:

{% gist https://gist.github.com/loremaps/feff3346d7376c4ea42a3fc981cdd59c %}

During our CI build process, we will replace the VERSION string with our Commit SHA, using the sed utility. To be honest, I wish there was a better way to pass environment variables at build time. This a highly requested feature:

[Request: Method to pass environment variables during build vs file. · Issue #4318 · angular/angular-cli](https://github.com/angular/angular-cli/issues/4318)

Hopefully, this will be better in the future. For now, sed tool will do the work.

### Create Gitlab CI

Thanks for being patient enough so far, and here is where everything falls into place. At the root of our angular application create our “ **_.gitlab-ci.yml_** ” file:

{% gist https://gist.github.com/loremaps/57eadccdb010468d940f3c3f5886ebc2 %}

In this file, we define three jobs as part of our CI pipeline:

1. Stage **build** : Build our angular app, but first replace the VERSION variable (as we explained in the previous section)
2. Stage **sentry** : Create our new release using the commit SHA and upload source map files. The $CI\_COMMIT\_SHA variable is pre-defined by GitLab.
3. Stage **deploy** : Upload dist folder to GitLab pages, but remove the source maps files.

The final configuration we need to do is to set the $SENTRY\_BASE\_TOKEN , $SENTRY\_BASE\_ORGANIZATION and $SENTRY\_BASE\_PROJECT variables. Let’s configure those into our GitLab group:

![](https://cdn-images-1.medium.com/max/1024/1*-_0gUpc_cthgDfbuJ7N4AA.png)

To get the Sentry Auth Token navigate here:

[Login | Sentry](https://sentry.io/settings/account/api/auth-tokens/)

Create a token with at least project:read, org:read and project:releases scopes.

### That’s it!

We are done! Now on every commit, GitLab will run our CI pipeline:

![](https://cdn-images-1.medium.com/max/833/1*fl-U0ueuyeJ3EdoncZDrmA.png)

Testing time! We will go to our published application and cause our fake exception. To find out the GitLab Pages URL, go to your repository under _Settings \> Pages_:

![](https://cdn-images-1.medium.com/max/675/1*sGPS8hYGHHDetWTx6bFeXA.png)

**Important Note:** The very first time it might take several minutes before your pages gets publicly available. Be patient!

We can now create click our button that cause the exception and let’s check what is logged on Sentry:

![](https://cdn-images-1.medium.com/max/1024/1*IXY9733a1W4Oavmm4EQ46w.png)<figcaption>Stack trace with source maps</figcaption>

🎉🎉🎉 There it is! The TypeScript code of your Angular app in the exception stack of Sentry! Let’s view them again, side by side for comparison.

![](https://cdn-images-1.medium.com/max/1024/1*lDSQsebiAJtm0hXPJJKtsQ.png)

![](https://cdn-images-1.medium.com/max/1024/1*IXY9733a1W4Oavmm4EQ46w.png)<figcaption>Stack traces before and after adding source maps</figcaption>

### Bonus

Since we are doing the release management in Sentry and we are associating the commits with our releases; Sentry is able to show the “suspect” commits for our exception:

![](https://cdn-images-1.medium.com/max/1024/1*P0aSbPE0nE1LINcIqsI0yA.png)<figcaption>Suspect commits</figcaption>

### Conclusion

When an exception occurs on production systems, having as much information as possible is imperative. Even more if we are talking about our source code. In this post we saw we can have our TypeScript source code from our Angular application available in the exception stack trace. Furthermore, we did it as part of our continuous integration pipeline. The process described here can be extended if you also use TypeScript with NodeJS.

The code for the Angular application can be found here: [https://gitlab.com/angular-sentry-demo/demo-ng-app](https://gitlab.com/angular-sentry-demo/demo-ng-app)

I hope you found it useful! 😃

Special thanks to [Pavlos Panagiotidis](https://medium.com/u/6d79ec0a00e8) for introducing me to these technologies and [Aristeidis Bampakos](https://medium.com/u/39abb62c7869) and [Stefanos Lignos](https://medium.com/u/ae9e2ee7d7f6) for the reviews! 👍

* * *