Angular - How to properly handle an HTTP error from server?

2k views Asked by At

Currently I've got this:

$http({
    method: 'POST',
    url: 'http://api-endpoint/somescript/',
    data: formData,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})
.then(function (response) {
    console.log(response);
});

If the script on the other end works out ok, then gets called. However, let's say the script on the server end has some sort of error that's not properly caught. If I make up an error by tossing in some garbage call like asdfasdf(), the then function isn't called, and instead I get this in the browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).

How do I catch this in the Angular code so I can handle it in a user-friendly manner?

EDIT: This is not a duplicate, as it is specific to Angular.

2

There are 2 answers

3
Matt On BEST ANSWER

The $q.then() method accepts three function parameters, the first being the handler for a successful callbacks, the second being for errors, and the third being for notify. $http leverages $q behind the scenes so this thenable should behave like the documentation suggests.

To handle errors in the above code, just toss in an additional function for error handling as such:

.then(function (response) {
    console.log(response);
}, function(response) {
    console.log(response);
});

Feel free to browse the $q documentation, specifically The Promise API, for additional details.

7
Nikhil Aggarwal On

To handle this, we will have to add a service/factory to intercept http calls. You can do it like this in your config

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

Now, the above service will be something like this

angular.module("app").factory('httpRequestInterceptor', function ($q) {

            return {
                'request': function (config) {

                    // Extract request information
                    return config || $q.when(config);
                },
                'responseError': function(rejection) {

                    // Extract response error information and handle errors
                    return $q.reject(rejection);
                 }
             }
        });