代码之家  ›  专栏  ›  技术社区  ›  nyg

使用Fetch API时捕获“加载资源失败”

  •  5
  • nyg  · 技术社区  · 7 年前

    window.onerror = (message, file, line, col, error) => console.log(error)
    window.addEventListener('error', (error) => console.log(error))
    
    try {
        fetch('https://www.bitstamp.net/api/ticker/').catch(e => {
            console.log('Caugth error:')
            console.log(e)
            console.log(JSON.stringify(e))
        })
    }
    catch (e) {
        console.log('try-catch')
        console.log(e)
    }
    

    我想捕捉的错误只出现在web控制台中:

    error messages

    请参阅此处的代码示例: https://github.com/nyg/fetch-error-test

    如何捕捉这些错误以提供屏幕消息?

    :实际执行了fetch的catch块。

    fetch('https://www.bitstamp.net/api/ticker/')
        .then(response => response.text())
        .then(pre)
        .catch(e => {
            pre(`Caugth error: ${e.message}`)
        })
    
    function pre(text) {
        var pre = document.createElement('pre')
        document.body.insertAdjacentElement('afterbegin', pre)
        pre.insertAdjacentText('beforeend', text)
    }
    pre {
        border: 1px solid black;
        margin: 20px;
        padding: 20px;
    }
    1 回复  |  直到 7 年前
        1
  •  3
  •   Schrodinger's cat    7 年前

    就我所记得的,你不能 catch try->catch 或者 catch chain fetch .

    抛出CORS异常的目的是让用户浏览站点,如果您可以调用它们,则知道此类异常,并保护被调用api/服务器上可能的安全信息的任何泄漏

    阅读 here 之前关于是否可以使用异常处理程序捕捉这些错误的讨论

    如果请求抛出的错误可能是响应的一部分,例如状态错误等,那么您可能会捕获它并显示自定义消息