top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Small Discuss about Angular App Exception Handling?

0 votes
532 views

What is Angular App Exception Handling?

The AngularJS $exceptionHandler service allows you to catch and handle unanticipated JavaScript errors in a meaningful way.

Example:
app.factory('$exceptionHandler',function($log,ErrorService) {
    return function(exception,cause) {
        if(console) {
        }
        
    }
    ErrorService.send(exception,cause);
});

Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console. In unit tests, if angular-mocks.js is loaded, this service is overridden by mock $exceptionHandler which aids in testing.

$exceptionHandler is very useful for sending errors to third party error logging services or helpdesk applications. Errors trapped inside of event callbacks are not propagated to this handler, but can manually be relayed to this handler by calling $exceptionHandler(e) from within a try catch block.

Video Tutorial for handling Exception Handling

posted Oct 18, 2016 by Parampreet Kaur

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Providers
A provider is the most sophisticated method of all the providers. It allows you to have a complex creation function and configuration options. A provider is actually a configurable factory.

var app = angular.module('myModule',[]);

app.provider("myProvider", function() {
    this.value = "My Value";

    this.setValue = function(newValue) {
        this.value = newValue;
    };

    this.$get = function() {
        return this.value;
    };
});

app.config(function(myProviderProvider) { // ADDED config section
    // Note the extra "Provider" suffix
    myProviderProvider.setValue("New Value");
});

Services

A service is an injectable constructor. If you want you can specify the dependencies that you need in the function. A service is a singleton and will only be created once by AngularJS. 

app.service("myProvider", function() { 
    this.getValue = function() {
        return "My Value";
    };
});

 

Factories
A factory is an injectable function. A factory is a lot like a service in the sense that it is a singleton and dependencies can be specified in the function. The difference between a factory and a service is that a factory injects a plain function so AngularJS will call the function and a service injects a constructor.

app.factory("myProvider", function() { 
    return "My Value";
});


Value
A value is nothing more than a simple injectable value. The value can be a string, number but also a function.

var app = angular.module('myModule',[]);

app.value("Value1", "First Value");
app.value("Value2", "Second  Value");


Constants

A constant can be injected everywhere. The value of a constant can never be changed.


var app = angular.module('myModule',[]);


app.constant("Constant1", "First Constant Value");
app.constant("Constant2", "Second Constant Value");

Video Tutorial

https://www.youtube.com/watch?v=jpT8vn5AhpY

READ MORE

Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object.

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

A new instance of deferred is constructed by calling $q.defer().

Methods:

  • Resolve(value)
  • Reject(reason)
  • Notify(notify)

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.

Methods:

  • then()
  • catch()
  • finally()


$q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.

Example Code:

var deferred = $q.defer();
var promise = deferred.promise;
 
promise.then(function success(data) {
  console.log('Success!', data);
}, function error(msg) {
  console.error('Failure!', msg);
});
 
deferred.reject('We failed :(');

Video about Angular Services

https://www.youtube.com/watch?v=cdG_T6ufcbE​

READ MORE

Interceptors define custom transformations for HTTP requests and responses at the application level. In other words, interceptors define general rules for how your application processes HTTP requests and responses.

An interceptor is simply a factory() service that returns an object with 4 properties that map to functions:

  • request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
  • requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  • response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
  • responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.


We activate an interceptor service by pushing that service into the $httpProvider.interceptors array in the config block of our application.
A session token can be added for all outgoing HTTP requests by adding it to the config.headers object in a request interceptor.
We can intercept HTTP response errors and handle specific errors by checking the response.status code.
$rootScope has limited utility when it comes to direct interaction, but it works well as an event bus as seen in the case of keeping our MainCtrl synchronized.

 

Example Code:

m.config(function($httpProvider) {
  $httpProvider.interceptors.push(function($q, $injector, userService) {
    return {
      request: function(request) {
        request.headers.authorization =
          userService.getAuthorization();
        return request;
      },
      // This is the responseError interceptor
      responseError: function(rejection) {
        if (rejection.status === 401) {
          // Return a new promise
          return userService.authenticate().then(function() {
            return $injector.get('$http')(rejection.config);
          });
        }

        /* If not a 401, do nothing with this error.
         * This is necessary to make a `responseError`
         * interceptor a no-op. */
        return $q.reject(rejection);
      }
    };
  });
});

 

Video for HTTP Interceptors

https://www.youtube.com/watch?v=K6W0kf6o_Zk​

READ MORE

How to use Angular.js Expressions,Numbers,Strings,Objects and Arrays

In Angular.js all Numbers,Strings,Object and Arrays are exactly similar to java script.

Angular.js Expressions

AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS expressions binds data to HTML the same way as the ng-bind directive.

AngularJS will "output" data exactly where the expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.

In each section i entered examples for both {{ expression }} and ng-bing.

AngularJS Numbers

AngularJS numbers are like JavaScript numbers:

Example Using expression:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

Total in dollar : 5

Same example using ng-bind:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

OutPut:

Total in dollar:5

AngularJS Strings

AngularJS strings are like JavaScript strings:

Example Using expression:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="firstName='manish';lastName='tiwari'">

<p>The full name is: {{ firstName + " " + lastName }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output :

The full name is: manish tiwari

Same example using ng-bind:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="firstName='manish';lastName='tiwari'">

<p>The full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output :

The full name is: manish tiwari

AngularJS Objects

AngularJS objects are like JavaScript objects:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="person={firstName:'manish',lastName:'tiwari'}">

<p>The name is {{ person.lastName }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The name is tiwari

Same example using ng-bind:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="person={firstName:'manish',lastName:'tiwari'}">

<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The name is tiwari

AngularJS Arrays

AngularJS arrays are like JavaScript arrays:

Example Using Expressions:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The third result is 19

Same example using ng-bind:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The third result is 19
READ MORE

How to Start Angular.js & How to Extend html in Angular.js?

AngularJS is a JavaScript framework. It can be added to an HTML page with a tag.

AngularJS is a JavaScript framework. It is a library written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

How to Start Angular.js?

When writing an AngularJS app, we write the behavior and interaction together alongside the presentation.

Writing this way can be confusing at first, especially if you have experience with other frameworks where the two are generally separate. Once you get the hang of it, it’ll become second nature.

Let’s look at the simplest app you can build with AngularJS:

Simple Example For Angular.JS

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  </head>
  <body>
    <div>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <h1>Hello, {{ yourName }}!</h1>
    </div>
  </body>
</html>

Output For The Above Code

enter image description here

In above text box what ever you type it will bind automatically in the header tag <h1></h1>

As you can see, you get bi-directional data binding without any work.

Bi-directional data binding means that if you change data on the back end, your changes will show up in your view automagically (actually, there’s no magic involved; we’ll get into how this works soon).

Similarly, if you change data in your view (e.g., by typing into a text box), it will automagically update your model.

So what did we do in our app?

ng-app
ng-model
= yourName
{{ yourName }}

First, we used our most important (and most easily forgotten) term: the ng-app attribute on the tag. Without this tag, the AngularJS process does not start.

Second, we told AngularJS that we want to set up bi-directional data binding on the yourName model on the page.

Third, we told AngularJS to display the data yourName in the directive template called {{ yourName }}.

How AngularJS Extends HTML ?

AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds element values (like the value of an input field) to the application.

The ng-bind directive binds application data to the HTML view.

Example Code:

<!DOCTYPE html>
<html>
<body>

<!-- Angular Directive Starts -->
<div ng-app="">

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p> <!-- Here ng-model binds the value of Input Filed -->
<p ng-bind="name"></p> <!-- Here binds application variable name to the innerHTML of a paragraph. -->

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Above Code Explanation

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the

element is the "owner" of an AngularJS application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds application variable name to the innerHTML of a paragraph.

Note:

Suppose,If you remove the ng-app directive, HTML will display the expression as it is, without solving it.

READ MORE

What is Angular.js?

AngularJS is an open-source web application framework. It is a structural framework for dynamic web apps.

It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly.

Its goal is to augment web applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier.

AngularJS is a MVC framework that defines numerous concepts to properly organize your web application.

Your application is defined with modules that can depend from one to the others. It enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML.

It also encapsulates the behavior of your application in controllers which are instanciated thanks to dependency injection.

AngularJS helps you structure and test your Javascript code very easily.

Finally, utility code can easily be factorized into services that can be injected in your controllers.

Some Main reasons for using Angular.js
1. MVC done right
2. A declarative user interface.
3.Write less code
4.DOM manipulations where they belong
5.Service providers where they belong
6.Context aware communication
7.Unit testing ready

Video Tutorial for What is Angular.js

https://www.youtube.com/watch?v=j1UmYUeqWuY

READ MORE
...