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.
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.
- 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
- 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: </strong><span data-ng-bind='errorMessage'></span></div>"
restrict: 'E'
)
- 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
- Use it
<!-- include the following place holder tag into your page -->
<x-error-messages></x-error-messages>
Written by Michael Engelhardt
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Angularjs
Authors
Related Tags
#angularjs
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#