angularjs error handling in ajax request

后端 未结 1 1174
广开言路
广开言路 2021-01-13 09:06

I want to write an error handling part in my application I use this code below but when error 500 occur its work right but there is a small or maybe big problem and thats th

相关标签:
1条回答
  • 2021-01-13 09:14

    I'm assuming that you are using angular ui-router.

    1st thing you need to add one state in your $stateProvider config to understand 'error' state by ui-router.

    Route config Code

    //added state to understand error
    $stateProvider.state("error": {
       url: "/error",
       templateUrl: '/views/error.html',
       controller: 'errorCtrl' //optional if you want any specific functionality
    });         
    

    And You did window.location and set the url, window.location causing page to refresh. Instead of using window.location use window.location.hash

    Interception function change

    var interceptor = ['$rootScope', '$q', '$location', function (scope, $q, $location) {
    function success(response) {
        return response;
    }
    
    function error(response) {
        var status = response.status;
        if (status == 500) {
          //window.location= "http://www.domain.lan/#!/error";
          //window.location.hash= "/error"; //it will rewrite the url without refreshing page
          $location.path('error');
          return;
        }
         if (status == 403) {
    
            // window.location = "dashboard";
            return;
        }
        // otherwise
        return $q.reject(responseInterceptors);
    
    }
    
    return function (promise) {
        return promise.then(success, error);
    }
    
    }];
    $httpProvider.responseInterceptors.push(interceptor);
    

    Other way you can try the same $state.go('error'); don't forget to add $state dependancy.

    Hope this will be helpful to you. Let me know if there is still any confusion.

    0 讨论(0)
提交回复
热议问题