ChrizTalk

Ionic/Angular server side error logging

September 30, 2015ChrizASP.NET MVC, IonicNo Comments
If you like it, please share it:

In this post I want to share my experiences on error logging in an Ionic Framework App.
By default Ionic/Angular is writing exceptions to the console of your browser, but what if you deployed your app to the app store and people start using it on their devices…
Maybe you write bugfree code, but it might still be a good practice to log unhandled exceptions somewhere you can monitor them.
That’s what this post is about.
In my case I worked on an app that has an ASP.NET Web API backend, which uses Elmah for error logging, so that’s what I’ll write about in this post, but you could use any server side technology.

For the Ionic part (or Angular) you’ll first have to override the default exception handler like this:

angular.module('myIonicApp', [])
    .factory('$exceptionHandler',[ '$injector', '$filter', function ($injector, $filter) {
        return function (exception, cause) {
            var data = {
                type: 'My Ionic App',
                url: window.location.hash,
                localtime: $filter('date')(Date.now(), 'dd-MM-yyyy HH:mm:ss')
            };
            if (cause) { data.cause = cause; }
            if (ionic.Platform) { data.platform = ionic.Platform.platform(); }
            if (exception) {
                if (exception.message) { data.message = exception.message; }
                if (exception.name) { data.name = exception.name; }
                if (exception.stack) { data.stack = exception.stack; }
            }
            var logService = $injector.get('logService');
            logService.logToServer(data);
            //Don't throw exception anymore.
            //throw exception;
        };
    }]);

As you can see, I’ll create a data object to store some information and then send it to the log service. The $injector is a workaround for a circular dependency problem with the logService($http).
I’ve commented out the throw exception (last line of the factory function), so the exception isn’t thrown anymore, depending on you scenario you might want to uncomment it again.
Below is the logService factory code, that’s called in the exception handler.

   .factory('logService', function ($http) {
        return {
            logToServer: function (data) {
                 $http.post('http://your-server.com/api/log', data);
            }
        };
   })

If you’re using this in an Ionic app, you should probably install the whitelist plugin to allow network requests to your log server, see https://github.com/apache/cordova-plugin-whitelist.

That’s it for the Ionic/Angular part, now the server part.

As mentioned before I’m using ASP.NET Web API as a backend server. I’ve added Elmah for error handling, there’s a NuGet package for installation: https://www.nuget.org/packages/elmah
Next add the code code to the ApiController.

        [HttpPost]
        [Route("api/coupon/log")]
        public IHttpActionResult Log(LogRequest request)
        {
            ErrorSignal.FromCurrentContext().Raise(new Exception(request.ToString()));
            return Ok();
        }
        //TODO: Move this to a seperate class/file
        public class LogRequest
        {
            [JsonProperty("type")]
            public string Type { get; set; }
            [JsonProperty("cause")]
            public string Cause { get; set; }
            [JsonProperty("platform")]
            public string Platform { get; set; }
            [JsonProperty("url")]
            public string Url { get; set; }
            [JsonProperty("localtime")]
            public string LocalTime { get; set; }
            [JsonProperty("message")]
            public string Message { get; set; }
            [JsonProperty("name")]
            public string Name { get; set; }
            [JsonProperty("stack")]
            public string Stack { get; set; }
            public override string ToString()
            {
                var sb = new StringBuilder();
                string newLines = Environment.NewLine + Environment.NewLine;
                sb.Append(String.Format("Type: {0}{1}", Type, newLines));
                sb.Append(String.Format("Cause: {0}{1}", Cause, newLines));
                sb.Append(String.Format("Platform: {0}{1}", Platform, newLines));
                sb.Append(String.Format("Url: {0}{1}", Url, newLines));
                sb.Append(String.Format("LocalTime: {0}{1}", LocalTime, newLines));
                sb.Append(String.Format("Message: {0}{1}", Message, newLines));
                sb.Append(String.Format("Name: {0}{1}", Name, newLines));
                sb.Append(String.Format("Stack: {0}{1}", Stack, newLines));
                return sb.ToString();
            }
        }

Based on you Elmah settings you will now be able to see all the errors from your Ionic app on your website, in your database or get an email notification.
I will not cover this in this blog post, since there’s a lot of documentation about it on their homepage, or the web…
Good luck!


If you like it, please share it:
Previous Post iOS push notifications using Ionic framework Next Post Angular 2 show/hide password component

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Ionic 3 and Firebase Facebook authentication using AngularFire2
  • Ionic 3 and Firebase authentication using AngularFire2
  • Ionic 3, Firebase and AngularFire2
  • Ionic 2 and Font Awesome using Sass
  • Using Google Fonts in Ionic 2

My Ionic 2 Theme

Please have a look at my new Ionic 2 theme.

&copy 2016 ChrizTalk