Handle 422 Status in AngularJS using Http Interceptors

June 14, 2016 | No Comments | Programming | angularjs http validation

Suppose we want to validate our forms on server side and handle it properly on client side. We can do this using AngularJs and http interceptors.

Let’s take a look on interested http status from Http extension for WebDav.

Here is the quote:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

This status fits perfectly for our validation error. Server will return this status only in this case.

Now we can implement simple $http interceptor on our client side to handle all error and show to users.

Let’s imagine we have simple 422 response from our server that looks like:

{"first_name":["The first name field is required."],"last_name":["The last name field is required."]}

Let’s set up our interceptor. This interceptor parses our messages and show user in grow like window. You can check angular-inform.

app.factory('StatusInterceptor', function ($q, $location,$injector,inform) {
    return {
        response: function(response){
            return response || $q.when(response);
        },
        responseError: function(rejection) {
 
            //Handle other statuses..
 
            if(rejection.status == 422){
                angular.forEach(rejection.data, function(value) {
                    angular.forEach(value, function(message) {
                        inform.add(message, {
                            "type": "danger"
                        });
                    });
                });
            }
 
            return $q.reject(rejection);
        }
    }
});

Now. we need to add our interceptor in application:

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push("StatusInterceptor");
});

That’s all. Now we don’t need to parse errors in every promise. Our http interceptors will handle all errors.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT