Improved both api request() in zabbixAPI and zabbixAPIService.

Improved api request error handling.
This commit is contained in:
Alexander Zobnin
2016-01-31 15:06:36 +03:00
parent 1d3e2337a2
commit 63cb31003c
2 changed files with 33 additions and 30 deletions

View File

@@ -20,7 +20,7 @@ function (angular, _) {
this.url = api_url;
this.username = username;
this.password = password;
this.auth = null;
this.auth = "";
this.requestOptions = {
basicAuth: basicAuth,
@@ -38,7 +38,6 @@ function (angular, _) {
p.request = function(method, params) {
var self = this;
if (this.auth) {
return ZabbixAPIService.request(this.url, method, params, this.requestOptions, this.auth)
.then(function(result) {
return result;
@@ -46,25 +45,22 @@ function (angular, _) {
// Handle errors
function(error) {
if (error.message === "Session terminated, re-login, please.") {
throw 'expired';
return self.login().then(function(auth) {
self.auth = auth;
return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
if (isAuthError(error.data)) {
return self.loginOnce().then(function() {
return self.request(method, params);
});
}
});
} else {
// Login first
//throw 'unauthenticated';
return self.loginOnce().then(function(auth) {
self.auth = auth;
return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
});
}
};
function isAuthError(message) {
return (
message === "Session terminated, re-login, please." ||
message === "Not authorised." ||
message === "Not authorized."
);
}
/**
* When API unauthenticated or auth token expired each request produce login()
* call. But auth token is common to all requests. This function wraps login() method
@@ -78,6 +74,7 @@ function (angular, _) {
self.loginPromise = deferred.promise;
self.login().then(function(auth) {
self.loginPromise = null;
self.auth = auth;
deferred.resolve(auth);
});
} else {

View File

@@ -17,6 +17,7 @@ function (angular) {
* @return {object} response.result
*/
this.request = function(api_url, method, params, options, auth) {
var deferred = $q.defer();
var requestData = {
jsonrpc: '2.0',
method: method,
@@ -24,8 +25,12 @@ function (angular) {
id: 1
};
if (auth === "") {
// Reject immediately if not authenticated
deferred.reject({data: "Not authorised."});
return deferred.promise;
} else if (auth) {
// Set auth parameter only if it needed
if (auth) {
requestData.auth = auth;
}
@@ -46,19 +51,20 @@ function (angular) {
requestOptions.headers.Authorization = options.basicAuth;
}
return backendSrv.datasourceRequest(requestOptions).then(function (response) {
backendSrv.datasourceRequest(requestOptions).then(function (response) {
// General connection issues
if (!response.data) {
return [];
deferred.reject(response);
}
// Handle Zabbix API errors
else if (response.data.error) {
throw new ZabbixException(response.data.error);
deferred.reject(response.data.error);
}
return response.data.result;
deferred.resolve(response.data.result);
});
return deferred.promise;
};
/**