Loopback + Rollbar

2 minute read Published:

Table of Contents

Loopback + Rollbar

Recently I have worked with loopback.io, a highly-extensible, open-source Node.js framework. In their website they describe it like that

LoopBack is a highly-extensible, open-source Node.js framework that enables you to:

  • Create dynamic end-to-end REST APIs with little or no coding.
  • Access data from major relational databases, MongoDB, SOAP and REST APIs.
  • Incorporate model relationships and access controls for complex APIs.
  • Use geolocation, file, and push services for mobile apps.
  • Easily create client apps using Android, iOS, and JavaScript SDKs.
  • Run your application on-premises or in the cloud.

I want it to use also a error tracking for the API that I was developing, for that I had chosen Rollbar.

Rollbar gives you the context and insights you need to find and fix bugs faster. Keep your software healthy and users happy.

Lets put every together

First we need to install the depencies:

$ npm install --save rollbar

Then we need to include and initialize the rollbar library with your access token

var rollbar = require('rollbar');
rollbar.init("<your-rollbar-access-token>");
In the Rollbar documentation is written that when we use a express webserver (as is the case with loopback), we only need to add this to our expres server.
app.use(rollbar.errorHandler('<your-rollbar-access-token>'));
But the REST adapter for strong-remoting sets up its own error handler! So you cannot accomplish this for REST API related calls by replacing:

  1. app.use(loopback.errorHandler()); in server/server.js

  2. or, loopback#errorHandler in middleware.json

Instead of that we need to add the error handler callback function to server/server.js as follows:

// at the very bottom of server.js
app.get('remoting').errorHandler = {
  handler: function(error, req, res, next) {
    if (error instanceof Error && error.status >= 500) {
        console.log(error.status);
        rollbar.handleError(error);

    }
    next(); /* let the default error handler (RestAdapter.errorHandler) run next */
  },
  disableStackTrace: true
};
Now we forward all internal server error that will be produced in the API. Note I have add
error.status >= 500
so it doesnt track the 40X error that are not important for my use case.

Now if we go to our rollbar dashboard we should see the error.

Hope you like that post ;)

References

Instructions for customising REST errorHandler

Rollbar Doc

comments powered by Disqus