【问题标题】:How to track 404 error without using XMLHttpRequest如何在不使用 XMLHttpRequest 的情况下跟踪 404 错误
【发布时间】:2020-05-27 03:42:25
【问题描述】:

这是一个播放音频文件并在音频完成后解析承诺的简单代码:

// our function
function audioPlay(source){

  let audio = new Audio(`${source}`);
  audio.crossOrigin = 'anonymous';
  audio.play();
  
  return new Promise((resolve) => {

  audio.addEventListener("ended", function(){  
  audio.currentTime = 0;          
  resolve();          
  }); 

  }); 
}

// play the audio after 3 seconds
setTimeout(() => play(), 3000);

// I created this function to show that resolving is working
async function play(){
	
     await audioPlay('myAudio.mp3');
     console.log('Resolved correctly..');

}

第一个场景:音频源是正确的,音频播放完毕,promise 解决,我们看到console.log('Resolved correctly..');

第二种情况:来源不正确(没有这样的文件)然后我们有这些错误:

获取https://example.com/play/myAudio.mp3404

Uncaught (in promise) DOMException: Failed to load because no 找到了支持的来源。

我想跟踪第二种情况,更清楚地说,我想跟踪 404 错误。为什么?

因为如果没有具有给定源的音频文件,我想播放另一个音频,例如哔声。

有什么解决办法吗?请帮忙...

注意:我知道我们可以使用如下函数检查文件是否存在:

function fileExist(url) {

    return new Promise((resolve) => {   

        const xhr = new XMLHttpRequest();
        xhr.open('HEAD', url, true);

        xhr.onload = function () {
        return resolve(xhr.status==200)
        };
        xhr.onerror = function () {
         return resolve(xhr.status==200)
      };

        xhr.send();

    });

}

但我在这里寻找跟踪 404 错误。这个函数应该是最后一个选项。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    为其添加错误处理程序

    function audioPlay(source) {
    
      return new Promise((resolve, reject) => {
    
        let audio = new Audio(`${source}`);
        audio.crossOrigin = 'anonymous';
        audio.addEventListener('error', function(e) {
          resolve({ error: e, mediaError: audio.error })
        })
        audio.addEventListener("ended", function() {
          audio.currentTime = 0;
          resolve({ complete: true });
        });
        audio.play();
      });
    }
    
    // play the audio after 3 seconds
    setTimeout(() => play(), 3000);
    
    // I created this function to show that resolving is working
    async function play() {
    
      const result = await audioPlay('myAudio.mp3');
      if (result.error) {
        console.log(result.mediaError)
      } else {
        console.log('Resolved correctly..');
      }
    
    }

    【讨论】:

      【解决方案2】:

      您可以尝试将await 包装在try ... catch 中。我认为这应该可行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-27
        • 2013-12-31
        • 2017-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        相关资源
        最近更新 更多