Google JavaScript API:捕捉HTTP错误 [英] Google JavaScript API: catching HTTP errors

查看:136
本文介绍了Google JavaScript API:捕捉HTTP错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亚伯拉罕 Google日历API:后端错误代码503 正好描述了我的情况。在循环创建或删除日历条目的代码时,我随机获得503个。然而,我无法弄清楚如何遵循他从Google引用的建议,即通过指数后退来捕获错误并重试交易。 / p>

下面的代码是一个将8个新事件放到我的日历中的循环。它会随机体验503错误,这些错误是由Google API而非我自己的代码引发的。很多时候它没有错误。

Google API代码与我的循环异步运行,因此在我的循环完成之前,没有任何Google操作会执行。当异步代码抛出503时,围绕我的代码的 try-catch 块不会触发。我不能放置 catch 放入回调函数中,而不是 try ,这样就会缩小 catch 的范围,以排除Google的代码。



有什么建议吗?

  / *适用于全天Google日历活动的特殊日期字符串格式。 
时区独立。
* /
Date.prototype.yyyy_mm_dd = function(){
var yyyy = this.getFullYear()。toString();
var mm =(this.getMonth()+ 101).toString()。slice(-2); //获得前导0
var dd =(this.getDate()+ 100).toString()。slice(-2);
return yyyy +' - '+ mm +' - '+ dd;
}

var fastevent = {
'summary':'Fast',
'organizer':{
'self':true,
'displayName':'Wes Rishel',
'email':'wrishel@gmail.com'},
'start':{'date':'zzzz'},//填入对于每个实例
'end':{'date':'zzzz'},
'colorId':'11',
}

function addFastEvents() {
尝试{
var eventDate = calendar.getLastFastDate()||新日期;
for(var eventCount = 0; eventCount< 8; eventCount ++){

//前进到下周二或周五
eventDate = eventDate.addDays(
[ 2,1,3,2,1,4,3] [eventDate.getDay()]
);
fastevent.start.date = eventDate.yyyy_mm_dd();
fastevent.end.date = fastevent.start.date;
var request = gapi.client.calendar.events.insert({
'calendarId':'primary',
'resource':fastevent
});
request.execute(function(fastevent){});
calendar.getPage(eventDate);
calendar.setCellStyle(eventDate,'fastingweekdaydata');
} //为
} catch(e){
p(e.message,e.name)
}
}


解决方案

指数退避是一种奇特的方式,表示在每次尝试时,您都会以指数方式增加等待时间,在放弃请求之前,您需要多次。

实现指数退避


指数退避是一种标准的错误处理策略,网络
应用程序,其中客户机定期在不断增加的时间内重试失败的请求
。如果大量请求或
繁重的网络流量导致服务器返回错误,那么指数
的退避可能是处理这些错误的好策略

这里有一个 JS代码演示代码,可能会给你一个想法:

  console.log = consoleLog; 

exponentialBackoff(有时是函数,10,100,函数(结果){
console.log('结果是',结果);
});

//继续尝试的函数,toTry​​,直到它返回true或具有
//尝试max次数。首先重试延迟延迟。
//回调在成功时被调用。
function exponentialBackoff(toTry,max,delay,callback){
console.log('max',max,'next delay',delay);
var result = toTry();

if(result){
callback(result);
} else {
if(max> 0){
setTimeout(function(){
exponentialBackoff(toTry,--max,delay * 2,callback);
},延迟);

}其他{
console.log('我们放弃');




函数有时会失败(){
var percentFail = 0.8;

返回Math.random()> = 0.8;


function consoleLog(){
var args = [] .slice.apply(arguments);

document.querySelector('#result')。innerHTML + ='\ n'+ args.join(' - ');
}


Abraham's answer to Google Calendar API : "Backend Error" code 503 exactly describes my situation. I get 503s at random places when looping through code that creates or deletes calendar entries.

However, I can't figure out how to follow the advice that he cites from Google, which is to catch the error and retry the transaction using exponential back off.

The code below is a loop that puts 8 new events into my calendar. It randomly experiences 503 errors, which are thrown from the Google API instead of my own code. Many times it works without an error.

The Google API code runs asynchronously from my loop, so none of the Google actions actually execute until my loop is done. The try-catch block surrounding my code doesn't fire when the async code throws a 503. I can't put a catch into the callback function without a try, and that would narrow the scope of the catch to exclude Google's code.

Any suggestions?

/* Special date string format for all-day Google Calendar events.
   Time zone independent.
 */
Date.prototype.yyyy_mm_dd = function() {
    var yyyy= this.getFullYear().toString();
    var mm  = (this.getMonth()+101).toString().slice(-2); //get leading 0
    var dd  = (this.getDate()+100).toString().slice(-2);
    return yyyy+'-'+mm+'-'+dd;
}

var fastevent = {
    'summary': 'Fast',
    'organizer': {
        'self': true, 
        'displayName': 'Wes Rishel', 
        'email': 'wrishel@gmail.com'},
    'start': {'date': 'zzzz'},      // filled in for each instance
    'end': {'date': 'zzzz'},
    'colorId': '11', 
}

function addFastEvents() {
    try {
        var eventDate = calendar.getLastFastDate() || new Date;
        for (var eventCount = 0; eventCount < 8; eventCount++) {

            // advance to next Tuesday or Friday
            eventDate=eventDate.addDays(
                [2, 1, 3, 2, 1, 4, 3][eventDate.getDay()]
            );
            fastevent.start.date = eventDate.yyyy_mm_dd();
            fastevent.end.date = fastevent.start.date;
            var request = gapi.client.calendar.events.insert({
              'calendarId': 'primary',
              'resource': fastevent
            });
            request.execute(function(fastevent) {});
            calendar.getPage(eventDate); 
            calendar.setCellStyle(eventDate, 'fastingweekdaydata');
        } // for
    } catch(e) {
        p(e.message, e.name)
    }
}

解决方案

Exponential backoff is a fancy way of saying that at each attempt, you increase the wait time exponentially, for a certain number of times before giving up the request.

Implementing exponential backoff

Exponential backoff is a standard error handling strategy for network applications in which the client periodically retries a failed request over an increasing amount of time. If a high volume of requests or heavy network traffic causes the server to return errors, exponential backoff may be a good strategy for handling those errors

Here's a demo code in JS that might give you an idea:

console.log = consoleLog;

exponentialBackoff(sometimesFails, 10, 100, function(result) {
    console.log('the result is',result);
});

// A function that keeps trying, "toTry" until it returns true or has
// tried "max" number of times. First retry has a delay of "delay".
// "callback" is called upon success.
function exponentialBackoff(toTry, max, delay, callback) {
    console.log('max',max,'next delay',delay);
    var result = toTry();

    if (result) {
        callback(result);
    } else {
        if (max > 0) {
            setTimeout(function() {
                exponentialBackoff(toTry, --max, delay * 2, callback);
            }, delay);

        } else {
             console.log('we give up');   
        }
    }
}

function sometimesFails() {
    var percentFail = 0.8;

    return Math.random() >= 0.8;
}

function consoleLog() {
    var args = [].slice.apply(arguments);

    document.querySelector('#result').innerHTML += '\n' + args.join(' - ');
}

这篇关于Google JavaScript API:捕捉HTTP错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆