AngularJS. Using $http.get I $http.get the server to get a specific object. This object is either there or is missing. If he is, I get it and perform some actions. But, if not, I get an error in the console ...

404 (Not Found)

How do I intercept this error so as not to show it to the user in the console?

  • one
    No way - 404 (Not Found) will always appear in the console if such an answer came from the server - Grundy
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • Then the question is, is it good practice on the server to organize the architecture in such a way that, in the absence of data, an error is returned, and not, for example, an empty object? And, perhaps, the problem is somehow solved by the interceptors? Is it worth digging this way? - Andrei
  • @Andrew, the server should return an error. if implied. that if there is no data - there should be an error. - Grundy

2 answers 2

 $http({ method: 'GET', url: '/someUrl' }).then( function successCallback(response) {}, function errorCallback(response) { // обрабатываем ошибку }); 

response has the following keys:

data - {string | Object} - received response body from the server.

status - {number} - HTTP status code

headers - {function ([headerName])} - a getter to get headers.

config - {Object} - config of the request sent to the server

statusText - {string} - HTTP status text from server

     /*global angular*/ (function () { 'use strict'; angular .module('App') .factory('httpErrorResponceInterceptor', ['$q', '$injector', '$rootScope', '$log', httpErrorResponceInterceptor]); httpErrorResponceInterceptor.$inject = ['$q', '$injector', '$rootScope', '$log']; /** * Интерцептор для перехвата ответов сервера, которые содержат ошибку. * Реализует обработку ошибочных ответов сервера (http кодов). * Реагирует только на коды 400, 401, 403, 404, и 500 * * @name httpErrorResponceInterceptor */ function httpErrorResponceInterceptor($q, $injector, $rootScope, $log) { var self = {}; self.responseError = function (response) { var $http = $injector.get('$http'); var $state = $injector.get('$state'); var userFactory = $injector.get('userFactory'); var jsonRegexp = /^application\/json;\s*charset=[a-zA-Z0-9\-\_]+/i; var m; /** * Проверяем что нам прислал сервер и если это JSON, * то ищем там текст сообщения и показываем его. */ if((m = jsonRegexp.exec(response.headers()['content-type'])) !== null){ var response_data = angular.fromJson(response.data); if (response_data.messages && angular.isArray(response_data.messages) && response_data.messages.length > 0) { $log.debug("httpErrorResponceInterceptor:", response); $rootScope.ERROR_MESSAGES = response_data.messages; } } /** * Если пользователю для выполнения запроса необходима авторизация, * то сервер ответит кодом 401 */ if (response.status == 401){ /** * Делаем разлогин пользователя, тем самым очищая содержимое сессии. * Это предусмотрено на тот случай, если вдруг сессия сохранится в localStorage, * а cookies удалены. */ if(response_data.code && response_data.code !== 4001){ userFactory.LogOut(); } return $q.reject(response); } else if (response.status == 400){ return $q.reject(response); } else if (response.status == 403) { return $q.reject(response); } else if (response.status == 404) { //$state.go("404"); return $q.reject(response); } else if (response.status == 500) { return $q.reject(response); } return $http(response.config); }; return self; } })(); 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 

    And then in the config block of your application we do this:

     $httpProvider.interceptors.push('httpErrorResponceInterceptor'); 

    Well, of course, correct the code for yourself)) I am from my project scopipastil.