Last Updated: February 25, 2016
·
624
· me

AngularJS: Global fault handler

Read the original blog post http://blog.mindcrime-ilab.de/?p=457

AngularJS is a great framework simplifying the development of JavaScript applications. The following example shows how to setup a global error handler to notify the user about the applications state.

fault-handler_sample

To benefit from angulars super powers the global fault handler part visible to the user is encapsulated into an angular directive which is an easy but powerful way to enhance the HTML tag cloud with your own components. Building the handler involves roughly the following steps:

Note: For those who are not fluent in CoffeeScript the code can be 'compiled' to JavaScript on the CoffeeScript homepage using the 'Try CoffeeScript' tab.

  1. Add global fault handler and clear method
app.run ($rootScope, $log) ->
  ###
  # fault handler
  ###
  $rootScope.faultHandler = (data) ->
    $log.debug "[faultHandler] error data[#{data}]"
    # handle and process error data here
    # assign error message to global fault message
    $rootScope = "ERROR: #{data}"

  ###
  # clear fault
  ###
  $rootScope.clearFault = () ->
    $log.debug "[faultHandler] clearing fault[#{$rootScope.errorMessage}]"
    $rootScope.errorMessage = undefined 
  1. Create custom tag to include the error handler
'use strict'

angular.module('myApp')
  .directive('errorMessages', () ->
    template: "<div class='alert alert-danger' data-ng-show='errorMessage'><strong>Achtung:&nbsp;</strong><span data-ng-bind='errorMessage'></span></div>"
    restrict: 'E'
  )
  1. Refer to fault handler
  'use strict'

angular.module('myApp')
.controller 'UserprofilCtrl', ($scope, $rootScope, $log, UserProfilService) ->
    $scope.profil = $rootScope.user

    # query userprofile by UID
    result = UserProfilService.get({id: $scope.profil.uid})

    result.$promise.then (profil) ->
      $scope.profil = profil
      $rootScope.clearFault()
    .catch $rootScope.faultHandler
  1. Use it
<!-- include the following place holder tag into your page -->
<x-error-messages></x-error-messages>