使用 Axios 拦截器处理 HTTP 请求错误

发布于 2022-07-29 00:26:13 字数 1156 浏览 208 评论 0

默认情况下, Axios 错误消息只包含状态码。 这是一个合理的默认设置,但默认错误消息通常没有帮助。

const app = express();
app.get('*', (req, res) => {
  res.status(404).json({ message: `Could not find page ${req.url}` });
});
const server = await app.listen(3000);

const err = await axios.get('http://localhost:3000/test').
  catch(err => err);
// "Request failed with status code 404"
err.message;

值得庆幸的是,Axios 使转换错误变得容易,因此错误消息对您的应用程序有意义。 Axios 拦截器 允许您转换来自 Axios 的所有错误。

// Create an Axios instance to 
const client = axios.create();
// Interceptors take 2 parameters:
// Axios calls the first function if the request succeeds
// Axios calls the second function if the request fails
client.interceptors.response.use(
  res => res,
  err => {
    throw new Error(err.response.data.message);
  }
)
const err = await client.get('http://localhost:3000/test').
  catch(err => err);
// "Could not find page /test"
err.message;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

为人所爱

暂无简介

0 文章
0 评论
23 人气
更多

推荐作者

yangzhenyu123

文章 0 评论 0

lvzun

文章 0 评论 0

执笔绘流年

文章 0 评论 0

芯好空

文章 0 评论 0

始于初秋

文章 0 评论 0

谁与争疯

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文