简体   繁体   English

从外部脚本中的函数捕获错误

[英]Catch error from function within external script

I'm working with the Soundcloud API, but this question is about catching errors in general. 我正在使用Soundcloud API,但是这个问题通常是关于捕获错误的。

I try to load a track, and, due to some settings or restrictions specific to that track, get a 403 (Forbidden) response. 我尝试加载轨道,由于该轨道的某些设置或限制,我收到403 (Forbidden)响应。 This error is thrown within the soundcloud script which I'm loading in my <head> : 我正在<head>加载的soundcloud脚本中引发了此错误:

<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>

Later, in my client-side javascript: 稍后,在我的客户端javascript中:

SC.initialize({
    client_id: 'xxxx',
});
...
SC.resolve(`https://soundcloud.com/${trackUrl}`).then((response) => {
    this.track.setAttribute('src', `${response.stream_url}?client_id=xxxx`);
});

trackURL is a valid URL - it's the 'readable' url of the track, and it is resolving to the correct track ID, which I can see in the GET request error below: trackURL是有效的URL,它轨道的“可读” URL,它解析为正确的轨道ID,我可以在下面的GET请求错误中看到该ID:

In the console: 在控制台中:

api.js:26 GET https://api.soundcloud.com/tracks/276705791.json?client_id=20f6b95488a0ca8f2254e250e6b0b229 403 (Forbidden)

inspecting api.js:
const sendRequest = (method, url, data, progress) => {
  let xhr;
  const requestPromise = new Promise((resolve) => {
    const isFormData = global.FormData && (data instanceof FormData);
    xhr = new XMLHttpRequest();

    if (xhr.upload) {
      xhr.upload.addEventListener('progress', progress);
    }
    xhr.open(method, url, true);

    if (!isFormData) {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        resolve({responseText: xhr.responseText, request: xhr});
      }
    };

    xhr.send(data); // <-- LINE 26
  });

  requestPromise.request = xhr;
  return requestPromise;
};

Since I'm loading this script externally, I can't fuss with it. 由于我是从外部加载此脚本的,因此我不能大惊小怪。

Is there any way to watch for errors within my own javascript so I can prepare a fallback? 有什么办法可以查看我自己的javascript中的错误,以便我准备后备吗?

Update 更新资料

Joseph's answer below is what I needed - to look for the error in the resolve promise. 约瑟夫在下面的回答是我所需要的-在resolve承诺中寻找错误。 Soundcloud isn't too helpful with response messages, but I can now program a fallback. Soundcloud对响应消息的帮助不太大,但是我现在可以编写一个后备程序。 Updated code: 更新的代码:

    SC.resolve('https://soundcloud.com/jacquesgreene/you-cant-deny').then((response) => {
        this.track.setAttribute('src', `${response.stream_url}?client_id=20f6b95488a0ca8f2254e250e6b0b229`);
        this.element.addClass('ready');
    }, (error) => {
        myFallback();
    });

The easiest answer would be to consult the documentation. 最简单的答案是查阅文档。

Now this is XHR, which is asynchronous. 现在这是XHR,它是异步的。 You can't "catch" with your regular try-catch . 您不能使用常规try-catch来“捕获”。

The xhr operation, however, only checks for readyState 4. means the xhr completed regardless of the HTTP status, even 403, and just resolves the promise with the data ( responseText ) and the xhr object itself ( xhr ). 但是,xhr操作仅检查readyState4。这意味着xhr已完成,而与HTTP状态无关,甚至是403,并且仅使用数据( responseText )和xhr对象本身( xhr )来解决了promise。 The problem now is if that resolved value goes back to your SC.resolve call. 现在的问题是,该解析值是否返回到SC.resolve调用。

From here, it's all a wild guess (unless, again, you consult the documentation). 从这里开始,这都是一个疯狂的猜测(除非再次,请查阅文档)。 You can either inspect what response is in your callback, or try adding a reject callback in your call hope the API mapped it correctly as a failure. 您可以检查回调中的response ,也可以尝试在调用中添加拒绝回调,希望API正确地将其映射为失败。

SC.resolve(`https://soundcloud.com/${trackUrl}`).then((response) => {
    // What is `response` and what does it contain?
}, function(error){
    // Does this execute? If so, what is `arguments`.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM