如何捕获服务器错误 JS

how to catch the server error JS

本文关键字:JS 错误 服务器 何捕获      更新时间:2023-09-26

我正在学习JavaScript,通过反复试验,有时服务器没有响应,并在内部生成Internal Server Error (500),随着错误的累积,您开始滞后页面。

也许我以错误的方式组装代码? 还是我做了糟糕的功能组合?

即使我用 try/catch 捕获了 500 错误,并尝试调用函数update但我无法抓住他。

此外,有时 JSON 以空值显示,并发送错误。我是否适合捕获错误?

这是代码。

jsfiddle.net/rocr/pa0221k6/

    var width = $('.ticker-text').width(),
    containerwidth = $('.ticker-container').width(),
    left = containerwidth;
    var timer;
$(document).ready(function(e){
//timer
function Timer(callback, delay) {
    var timerId, start, remaining = delay;
    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };
    this.resume = function() {
        start = new Date();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    };
    this.resume();
}

//show stock quotes    
function update() {
    var query = "select * from yahoo.finance.quotes where symbol = ";
    var symbolo = "'aapl'"; 
    var yql = "http://query.yahooapis.com/v1/public/yql?q=" + escape(query+symbolo) + "&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=?";
    var xhr2 = $.ajax({ 
        url: yql,
        jsonp: "myCallback",
        dataType: 'json', 
        success: function(data) {
            var keys = data.query.results.quote;
            $("#a").html(keys.LastTradePriceOnly);
            $("#b").html(keys.LastTradePriceOnly);
            update();
        }, 
        error: function(xhr, ajaxOptions, thrownError) {
            //console.log(xhr.status + " , " +thrownError);
            //console.log('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
            update();
        },
        statusCode: {
            500: function() {
                console.log( "Error 500" );
                alert( "Error 500" );
                update();
            }
        },
        timeout: 3000
    });
}

//move div    
function tick() {
        if(--left < -width){
            left = containerwidth;
        }
        $(".ticker-text").css("margin-left", left + "px");
        //setTimeout(tick, 16);
        timer = new Timer(tick, 16);
      }
      tick();
      update();
        $("#b").hover(function(){
        timer.pause();
        $("#b").css("background-color", "yellow");
        },function(){
        timer.resume();
        $("#b").css("background-color", "pink");
        });
});

如果未处理 ajax 请求,则再次使用 try 来处理 DOM 中的显示。

success: function(data) {
  try{
    var keys = data.query.results.quote;
    var keys = data.query.results.quote;
    $("#a").html(keys.LastTradePriceOnly);
    $("#b").html(keys.LastTradePriceOnly);
    update();
  }
}