Javascript 获取API:处理错误的URL

Javascript 获取API:处理错误的URL,javascript,fetch-api,Javascript,Fetch Api,我想要防弹一些代码,它接受用户输入并尝试从URL获取数据 我有如下几点: fetch(url) .then(response=>{ console.log(response.ok); response.text(); }) .catch(error=>console.log(error)); 在实际代码中还有更多的内容 如果我输入类似http://rubbish我捕捉到一个类型错误,我可以处理它。如果输入类似于垃圾(没有http://协议)的内容,则会出现如下错误:

我想要防弹一些代码,它接受用户输入并尝试从URL获取数据

我有如下几点:

fetch(url)
.then(response=>{
    console.log(response.ok);
    response.text();
})
.catch(error=>console.log(error));
在实际代码中还有更多的内容

如果我输入类似
http://rubbish
我捕捉到一个
类型错误
,我可以处理它。如果输入类似于
垃圾
(没有
http://
协议)的内容,则会出现如下错误:

GET file:///…/rubbish net::ERR_FILE_NOT_FOUND
然后获取我的
TypeError
。实际错误发生在上面代码的第一行,在
catch()
块之前

处理这种错误的正确方法是什么


我在一个Electron应用程序中这样做,所以我不必担心浏览器的兼容性。

根据错误类型,您可能会在
catch
块中执行不同的逻辑。例如:

fetch(url)
.then(response=>{
    console.log(response.ok);
    response.text();
})
.catch(
    if (err instanceof TypeError) {
        // Handle this normally
    } else {
        // Execute other logic depending on the type of error you are receiving
    }
);

希望这有帮助,祝你好运:)

你的意思是URL应该始终是绝对URL吗?你能检查输入中的协议吗?^https?:\/\/,如果缺少,请进行预处理?@skyboyer它必须是,因为它将作为桌面应用程序运行。但是,我可以看出它可能将字符串解释为相对URL?@Anthony如果有必要,我可以很容易地做到这一点。
fetch()
没有其他内容吗?@Manngo您可以检查
then()
中的
response.status===404
?根据控制台,在执行提取的行中发生错误。
捕获
正在拾取异常。