reactjs - 抛出错误给我 API 错误,而不是我写的
问题描述
使用 Fetch,我试图让我的代码返回我写的自定义错误消息,而不是来自 api 的响应错误消息。
在此示例中,我不想使用“自定义错误消息”,因为我得到“无法获取”。我只知道我是否尝试使用其他 API。有时它会起作用。
我究竟做错了什么?
export default function App() {
const [loading, setLoading] = useState(true)
const [api, setApi] = useState("")
const [error, setError] = useState("")
useEffect(() => {
fetch("url")
.then(res => {
if(!res.ok){
throw Error("CUSTOM ERROR MESSAGE")
}
return res.json()
})
.then(data => {
setApi(data)
setLoading(false)
})
.catch(error => {
setError(error)
setLoading(false)
})
}, [])
console.log(error)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{
loading === "" ? <h1>loading...</h1> : <h1>{api.name}</h1>
}
{
error === "" ? "" : <h1>{error}</h1>
}
</div>
);
}
解决方案
推荐阅读
- python - ValueError 和 ZeroDivisionError
- sql - 从触发器插入的 SQL 更新
- asp.net-core - 如何使用 Tag Helpers 创建从区域页面到根页面文件夹的链接?
- php - LARAVEL SQLSTATE [HY000]:一般错误:1364 字段“电话号码”没有默认值
- c++ - 如何在 Qprocess 中运行 FFmpeg 命令以使其工作?
- php - PHP:var_dump 输出未满
- python - 在 Python Pandas 数据框中的列中按 max 查找分组并标记它的最快方法是什么?
- r - 有没有办法从 ggplot2 中的回归图中获取梯度值?
- python - 如何选择 numpy 张量点轴
- mysql - SQL 跨多个表选择第 N 行和分组依据