Wednesday, April 29, 2015

Centralize client side exception handling mechanism in AngularJS

Exception handling feature is common in all web application. If you are ASP.NET developer then probably you have used some kind of filter in Global or Controller level to implement centralize exception handling mechanism. It’s fine when we want to handle exception in server.

But let’s think one situation where some kind of framework (read AngularJS) has used to make http call (ajax) and we have to handle server exception in client side.

Now, let me explain real problem, which I face few days ago. I used Authorizatin filter to check authorization of user and my client code was based on AJAX call, so there was no post back at all. When session was time out IIS simply throws 401(unauthorized) exception and I started to capture this in each and every AJAX call and I did not accept this practice from my heart.

So, started to think to implement something using AngularJS where I can handle all exception in one place.  Here is the solution for it.

var myApp = angular.module("myApp", []);

This is definition of module and now we will use interceptors to capture response from server in AJAX call and from here we will return promise.

myApp.config(['$httpProvider', function ( $httpProvider) {

            $httpProvider.interceptors.push(function ($q, $rootScope) {
                return {
                    'responseError': function (rejection) {
                        var status = rejection.status;
                        var config = rejection.config;
                        var method = config.method;
                        var url = config.url;

                        if (status == 401) {
                            //Handle unauthorize error
                        } else {
                            //Handle other errors

                        return $q.reject(rejection);

This is pretty simple and clean . Now, we will implement one simple controller to perform AJAX call. Here is sample code.

myApp.controller('myController', function ($scope, $http, $q) {

            $http({ method: 'GET', url: '../Home/Process', cache: 'true' }).
                then(function (data) {

And here is action within Home Controller.

public class HomeController : Controller
        public string Process()
            throw new Exception("Error");

Just have a look on Process() action and we will see that it has decorated with Authorize action filter that mean if the user is not authorize then server will throw 401 error.

Most likely, you may redirect user to login page in this situation or some other generic page in case of other error.

No comments:

Post a Comment