AngularJS using interceptors to handle HTTP errors uniformly (reproduce)

Source: Internet
Author: User
Tags toastr

Original:http://chensd.com/2016-03/angular-handle-global-http-error-with-interceptors.html?utm_source=tuicool& Utm_medium=referral

In WEB development, in addition to data operations, the most frequent is the initiation and processing of various HTTP requests, plus the HTTP request is asynchronous, if in each request to capture a variety of common errors, processing various types of custom errors, there will be a lot of functional similar code, Or use an ugly method to call a few custom functions in each request to handle. These two methods are basically not a reliable choice. Fortunately, AngularJS provides the interceptors--interceptor fighter--to unify all XHR requests within the application.

Key Features

Interceptors has two processing opportunities, namely:

    • After the other program code executes the HTTP request, the request is processed before the request is actually made from the browser
    • After the requested response is received, the response to the request is processed before other program code is processed

Therefore, it is not difficult to understand that it can be used in the following areas:

    • Global processing error
    • A unified process for authenticating a class
    • Pre-processing of all requests sent out
    • Preprocessing of all received responses
    • Do something to enhance the user experience, such as displaying a progress bar
Basic use

First look at the most basic use:

var app = angular.Module' app ', []);

Define a Service, and wait for it to be treated as a interceptors function
App.factory (' Httpinterceptor ', [' $q ', Httpinterceptor]);

function Httpinterceptor($q) {
return {
Requestfunction(Config){
return config;
},
Requesterror:function(Err){
Return $q. Reject (ERR);
},
Responsefunction(Res){
return res;
},
Responseerror:function(Err) {
if (-1 = = = Err.status) {
Remote server Not responding
} Else if (= = = = Err.status) {
Handle a variety of custom errors
} Else if (501 = = = Err.status) {
// ...
}
return $q. Reject (ERR);
}
};
}

Add the corresponding interceptors
App. Config ([' $httpProvider ', function($httpProvider) {
$httpProvider. Interceptors.push (Httpinterceptor);
}]);
Further information

The actual interceptor processing function, a return four-member object, the four members are not required , you can specify one or two according to the actual situation, respectively, as follows:

    • request : Receives a parameter, which is the $http standard Config object in, and also needs to return a standard config , you can add a variety of authentication information, but also to start a progress bar here
    • requestError : When there are multiple interceptor, the requestError previous interceptor throws an error or executes when executed $q.reject() , and the received parameter corresponds to the error
    • response : Accept a Request object parameter, can be returned without processing, the progress bar can also be displayed as a successful completion, of course, if the backend API returns a custom error, the HTTP status code is still 200, then handle the custom error here, You can also do some processing on the returned data, taking care to set the progress bar to complete
    • responseError : This is the play, which can handle standard HTTP errors, such as when the server is not responding, or a CGI class such as PHP 5,021, can also handle the HTTP status code is not 200 of the various custom errors

Of the above four, the first two are the pre-processing of the request, and the latter two are the processing of the requested response.

A few related libraries

Show Progress:

    • Nprogress
    • Ngprogress nprogress for AngularJS
    • Rc-progress
    • Progress-full-width
    • Progress-svg

Prompt box:

    • Toastr
    • Ngtoast Toast for AngularJS
    • Angular-toast
    • K-toast
    • Notie
    • Ng-notie
    • Corner-notie
A complete example

See the code (Github, coding.net), examples of how to handle errors uniformly, use toastr hints, and use nprogress to display a progress bar.

AngularJS using interceptors to handle HTTP errors uniformly (reproduce)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.