[javascript] Error handling in AngularJS http get then construct

How can I handle an HTTP error, e.g. 500, when using the AngularJS "http get then" construct (promises)?

$http.get(url).then(
    function(response) {
        console.log('get',response)
    }
)

Problem is, for any non 200 HTTP response, the inner function is not called.

The answer is


Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }

You can make this bit more cleaner by using:

$http.get(url)
    .then(function (response) {
        console.log('get',response)
    })
    .catch(function (data) {
        // Handle error here
    });

Similar to @this.lau_ answer, different approach.


If you want to handle server errors globally, you may want to register an interceptor service for $httpProvider:

$httpProvider.interceptors.push(function ($q) {
    return {
        'responseError': function (rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
});

Docs: http://docs.angularjs.org/api/ng.$http


https://docs.angularjs.org/api/ng/service/$http

$http.get(url).success(successCallback).error(errorCallback);

Replace successCallback and errorCallback with your functions.

Edit: Laurent's answer is more correct considering he is using then. Yet I'm leaving this here as an alternative for the folks who will visit this question.


I could not really work with the above. So this might help someone.

$http.get(url)
  .then(
    function(response) {
        console.log('get',response)
    }
  ).catch(
    function(response) {
    console.log('return code: ' + response.status);
    }
  )

See also the $http response parameter.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to promise

Axios handling errors typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here Syntax for async arrow function Angular 2: How to call a function after get a response from subscribe http.post How to use fetch in typescript Returning Promises from Vuex actions Use async await with Array.map Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai using setTimeout on promise chain Why is my asynchronous function returning Promise { <pending> } instead of a value?

Examples related to angular-promise

Angular 1.6.0: "Possibly unhandled rejection" error What is the difference between Promises and Observables? How to access the value of a promise? How to return a resolved promise from an AngularJS Service using $q? Wait for all promises to resolve Error handling in AngularJS http get then construct AngularJS : Initialize service with asynchronous data How to cancel an $http request in AngularJS?

Examples related to angular-http

Angular 4.3 - HttpClient set params Angular 2 http post params and body How to read response headers in angularjs? AngularJs $http.post() does not send data Angularjs autocomplete from $http $http get parameters does not work Error handling in AngularJS http get then construct How to cancel an $http request in AngularJS? AngularJs ReferenceError: $http is not defined Processing $http response in service