Fetch API,你真的知道如何处理错误吗?
Fetch API 并不是那么新,大多数开发人员都曾使用它来从服务器检索资源,但您真的知道如何在使用此 API 时处理错误吗?
给出下面的代码,其中使用 Fetch API 的请求返回 404 错误,控制台中的消息是什么:成功还是失败?
try {
// this endpoint will return 404
const response = await fetch('https://restcountries.com/v4.1/all');
console.log('Success');
} catch {
console.error('Failed');
}
如果你认为这段代码会在发生 404 错误时记录失败消息,那么我认为这篇文章绝对适合你,因为你的答案是错误的。它console.log
会显示成功消息,我会告诉你原因,以及使用 Fetch API 处理错误的最佳方法是什么。
什么是 Fetch API?
简而言之,Fetch API 是一个用于轻松向端点发出异步 HTTP GET 和 POST 请求的接口。
我真的建议你阅读我之前写的这篇文章,名为“Fetch API 是 AJAX 的新旧版本”,其中我更好地解释了什么是 Fetch API 以及如何将它与 async/await 语法一起使用,所以请随意查看有关此 API 的更多解释。
如何使用 Fetch API 处理错误?
使用 Fetch API 时可能会出现各种错误,例如:服务器错误 (500)、未找到错误 (404)、网络错误、CORS 错误等等。我们提供了不同的方法来处理所有这些错误,如下所示。
使用 try/catch 处理 Fetch API 错误
我假设你熟悉 JavaScript 中的 Promise,并且知道它们的工作原理(因为 Fetch API 如此流行的原因之一就是它返回一个 Promise)。因此,我们可以利用 的强大功能then
,catch
以及finally
fetch 的解析、拒绝和完成状态。
将 fetch 调用包装在 try/catch 块中是处理错误的一种非常常见的方法(参见下面的示例),但并非所有错误都能被捕获,我将在代码之后解释这一点。
try {
// this endpoint will return CORS error
const response = await fetch('https://google.com/api');
} catch {
console.error('Failed');
}
// Output: Failed
此代码将尝试执行获取并仅当承诺被拒绝时检测错误(这可能发生在两种情况下):
- 网络错误:无法连接到服务器,这可能由多种原因引起,例如网络速度慢和超时。
- CORS 错误:当一个域未被授权从其他域获取资源时。
对于服务器状态错误(例如 404 和 500),Fetch 将返回已解决,这就是为什么在本文开头的示例中 catch 无法获取它们的原因。
检查响应状态以处理 Fetch API 错误
使用 Fetch API 处理错误的另一种常见方法是在承诺解决时检查响应状态 - 这就是我们在本文开头的示例中获取 404 错误的方式:
// this endpoint will return 404
const response = await fetch('https://restcountries.com/v4.1/all');
if (response.ok) {
// ...do something with the response if response.ok is true
} else {
console.error('Failed');
}
这里我们用来response.ok
检查响应是否成功(真或假)。
- 当
true
状态码在 200 到 299 之间时(表示成功)。 false
当服务器返回除上述状态以外的任何其他状态时。例如 404(未找到)和 500(内部服务器错误)。
使用 Fetch API 处理错误的最佳方法
示例 01
正如您上面所见,try/catchresponse.ok
用于捕获不同类型的错误,因此我们可以结合这两种方法,以便使用 Fetch API 更好地处理错误。参见以下示例:
try {
const response = await fetch('https://restcountries.com/v4.1/all');
if (response.ok) {
console.log('Promise resolved and HTTP status is successful');
// ...do something with the response
} else {
console.error('Promise resolved but HTTP status failed');
}
} catch {
console.error('Promise rejected');
}
解释:
- try/catch 用于在承诺被拒绝时获取错误(网络或 CORS 问题)
response.ok
用于在 Promise 得到解决时处理服务器错误(例如 404 或 500)
示例 02
在代码块中处理错误的另一种常见方法是,当isn'ttry
时抛出错误,以使代码块得以执行,这样我们就可以在同一位置处理所有错误。请参阅下面的示例以便更好地理解:response.ok
true
catch
try {
const response = await fetch('https://restcountries.com/v4.1/all');
if (response.ok) {
console.log('Promise resolved and HTTP status is successful');
// ...do something with the response
} else {
// Custom message for failed HTTP codes
if (response.status === 404) throw new Error('404, Not found');
if (response.status === 500) throw new Error('500, internal server error');
// For any other server error
throw new Error(response.status);
}
} catch (error) {
console.error('Fetch', error);
// Output e.g.: "Fetch Error: 404, Not found"
}
在这里,我们抛出错误并在 catch 块中处理它们,并且还根据错误的类型在控制台中显示自定义消息。
- 当
response.ok
返回 false 时,我们可以简单地抛出一个错误,因此 catch 块将被执行 - catch 将处理所有类型的错误
- catch 接受一个参数,该参数可以在从 try 块抛出错误时进行自定义
response.status
可用于检查返回的 HTTP 状态代码以在控制台中显示自定义消息(如 400、404、500……)。
参考
结论
处理使用 Fetch API 从服务器检索资源时可能发生的所有错误非常重要,在这里我解释了如何使用 try/catch 以及response.ok
获取response.status
不同的错误以及自定义我们处理它们的方式。
下次见!😁
文章来源:https://dev.to/dionarodrigues/fetch-api-do-you-really-know-how-to-handle-errors-2gj0