How to control the responses of http requests with angularjs

0

I would like to know how to handle exceptions in angularjs. What artifacts can I use or how to implement error handling.

I have the following code:

This is an example of my JSON. Now what I would like to validate is if the list "listProducts" exists or comes empty.

[{
    "estado":false,
    "id":1,
    "direccion":"Calle José Galvez 1575 Dpto 201 Lince",
    "tipodeFactura":"Facturación",
    "asociado":"998882591",
    "listadoProductos": [{
            "idProducto":"0001",
            "nombreProducto": "Cajita Feliz"
        }
    ],
    "fault":[{
        "errorFun":[{
            "idError":"01",
            "mensaje":"errorfunc"
        }],
        "errorTec":[{
            "idError":"01",
            "mensaje":"errorTec"
        }]
    }]  
}]

For example I have the following call $http from my service:

appServices.service('productoServicio', ['$http', function($http) {

    var UrlProductosServicios = 'http://172.19.74.235:8909/ProductoServiciosResulFull/service/obtenerServicios/p';

    this.getListProductos = function () {
        return $http.get(UrlProductosServicios);
    };

The field "fault" of the Json must bring the errors of coding, functionality, timeout or availability of the server. How can I implement the handling of these errors? Would you appreciate your help if you can give me some idea of how to handle this?

I also attach the method getListProductos of my service in my controller to my consumption

   productoServicio.getListProductos().then(function (response) {
            $scope.ListProducto  = response.data;
            $scope.estadoConsumer = true;
        }, function (error) {
            $scope.status = 'Unable to load customer data: ' + error.message;
            $scope.estado = false;     
        });

Thanks in advance

    
asked by jose.luis.lopez 20.06.2016 в 22:08
source

1 answer

2

What you want can be achieved with a interceptor for the response

The syntax is simple, create a factory that returns an object where the keys are functions to manipulate each part of the request

.factory('myInterceptor', function($q) {
    return {
      'request': function(config) {
          // esto se ejecutará antes de que se envíe cada petición
          // puedes modificar la configuración de todas las peticiones
          return config;
      },
      'requestError': function(rejection) {
          // esto se ejecutará cuando la petición tenga errores al enviar
          return $q.reject(rejection);
      },
      'response': function(response) {
          // esto se ejecutará cada vez que una petición retorne satisfactoriamente
          return response
      },
      'responseError': function(rejection) {
          // esto se ejecutará cada vez que una petición retorne con errores      
          return $q.reject(rejection);
      },
    }
  })

Each of the keys are optional. Then you just add it using $httpConfig in config block or $http in run block .

.config(function($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
})

You just need to examine the property fault of the object that arrives.

I'll give you an example:

angular.module('app', ['ngMockE2E'])
  .controller('MyCtrl', function($http) {
    $http.get('/foo');
  })
  .factory('errorInterceptor', function() {
    return {
      'response': function(response) {
        console.log(response.data.fault);
      }
    }
  })
  .config(function($httpProvider) {
    $httpProvider.interceptors.push('errorInterceptor');
  })
  .run(function($httpBackend) {
    $httpBackend.whenGET('/foo').respond([{
      "estado": false,
      "id": 1,
      "direccion": "Calle José Galvez 1575 Dpto 201 Lince",
      "tipodeFactura": "Facturación",
      "asociado": "998882591",
      "listadoProductos": [{
        "idProducto": "0001",
        "nombreProducto": "Cajita Feliz"
      }],
      "fault": [{
        "errorFun": [{
          "idError": "01",
          "mensaje": "errorfunc"
        }],
        "errorTec": [{
          "idError": "01",
          "mensaje": "errorTec"
        }]
      }]

    }]);
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
<div ng-app="app" ng-controller="MyCtrl"></div>
    
answered by 20.06.2016 в 23:55