使用 axios intercpetor 进行全局错误处理

发布于 2025-01-15 03:08:33 字数 4195 浏览 3 评论 0原文

我想测试错误句柄 当我输入“http://localhost:3000/announce/ks/123”时,我希望数据库中没有任何值,然后转到未找到页面或任何错误页面(例如 400、403,404、500 )

前端

  useEffect(() => {
    axios
      .get(`/api/announces/announce/ks/${AnnounceKSId}`, AnnounceKSId)
      .then((response) => {
        if (response.data.success) {
          setAnnounceKS(response.data.announceKS);
          setIntro(response.data.announceKS.intro); //배열로 저장된 intro의 경우 받아오는 순서 때문에 오류가 생기기떄문에 따로 받아준다.
          setDeadline(response.data.announceKS.deadline);
          setFiles(response.data.announceKS.files);
        }
      })
      .catch((err) => {
        // to manage error handling globally
        // to fix error 'unhandled promise rejection'
        // console.log("err", err);
      });
  }, [AnnounceKSId]);

...
export default CheckRequests(AnnounceKSDetail);

后端

router.get("/announce/ks/:announceKSId", (req, res) => {
  let announceKSId = req.params.announceKSId;
  AnnounceKS.findOne(
    { _id: announceKSId.match(/^[0-9a-fA-F]{24}$/) },
    (err, announceKS) => {
      return res.status(200).json({ success: true, announceKS });
    }
  )
    .then((announceKS) => {
      announceKS.views++;
      announceKS.save();
    })
    .catch((err) => {
      return res.status(400).json({ success: false });
    });
});

axios.interceptor

import React, { useEffect } from "react";
import axios from "axios";

const checkRequests = (Wrapped) => {
  function CheckRequests(props) {
    useEffect(() => {
      //then이나catch로 처리되기 전에 요청이나 응답을 가로챌 수 있습니다.
      axios.interceptors.response.use(
        function (response) {
          // / 요청을 보내기 전에 수행할 일
          return response;
        },
        function (error) {
          // 오류 요청을 보내기전 수행할 일
          switch (error.response.status) {
            case 400:
              props.history.push("/NotFound");
              break;
            case 403:
              props.history.push("/Forbidden");
              break;
            case 404:
              props.history.push("/NotFound");
              break;
            case 500:
              props.history.push("/InternalServerError");
              break;
            default:
              props.history.push("/NotFound");
              break;
          }
          return Promise.reject(error.response);
        }
      );
    });

    return <Wrapped {...props} />;
  }
  return CheckRequests;
};

export default checkRequests;

vscode 错误

[0] Server Listening on 5000
[0] MongoDB Connected
[0] The collection exists
[0] node:events:368
[0]       throw er; // Unhandled 'error' event
[0]       ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at new NodeError (node:internal/errors:371:5)
[0]     at ServerResponse.setHeader (node:_http_outgoing:576:11)
[0]     at ServerResponse.header (C:\projectb_back_세미\node_modules\express\lib\response.js:776:10)
[0]     at ServerResponse.send (C:\projectb_back_세미\node_modules\express\lib\response.js:170:12)
[0]     at ServerResponse.json (C:\projectb_back_세미\node_modules\express\lib\response.js:267:15)
[0]     at C:\projectb_back_세미\server\routes\announces.js:353:30
[0]     at C:\projectb_back_세미\node_modules\mongoose\lib\model.js:5074:18
[0]     at processTicksAndRejections (node:internal/process/task_queues:78:11)
[0] Emitted 'error' event on Function instance at:
[0]     at C:\projectb_back_세미\node_modules\mongoose\lib\model.js:5076:15
[0]     at processTicksAndRejections (node:internal/process/task_queues:78:11) {
[0]   code: 'ERR_HTTP_HEADERS_SENT'
[0] }
[1] [HPM] Error occurred while proxying request localhost:3000/api/users/auth to http://localhost:5000/ [ECONNRESET] (https://nodejs.org/api/errors.html#errors_common_system_errors)   
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] [HPM] Error occurred while proxying request localhost:3000/api/users/auth to http://localhost:5000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)

你能给我一些建议吗?

无论是否转到未找到页面(错误页面),我都会收到错误

I want to test error handle
when I put "http://localhost:3000/announce/ks/123" then I wish no value in my database then go to not found page or any error page(ex 400, 403,404, 500)

front-end

  useEffect(() => {
    axios
      .get(`/api/announces/announce/ks/${AnnounceKSId}`, AnnounceKSId)
      .then((response) => {
        if (response.data.success) {
          setAnnounceKS(response.data.announceKS);
          setIntro(response.data.announceKS.intro); //배열로 저장된 intro의 경우 받아오는 순서 때문에 오류가 생기기떄문에 따로 받아준다.
          setDeadline(response.data.announceKS.deadline);
          setFiles(response.data.announceKS.files);
        }
      })
      .catch((err) => {
        // to manage error handling globally
        // to fix error 'unhandled promise rejection'
        // console.log("err", err);
      });
  }, [AnnounceKSId]);

...
export default CheckRequests(AnnounceKSDetail);

back-end

router.get("/announce/ks/:announceKSId", (req, res) => {
  let announceKSId = req.params.announceKSId;
  AnnounceKS.findOne(
    { _id: announceKSId.match(/^[0-9a-fA-F]{24}$/) },
    (err, announceKS) => {
      return res.status(200).json({ success: true, announceKS });
    }
  )
    .then((announceKS) => {
      announceKS.views++;
      announceKS.save();
    })
    .catch((err) => {
      return res.status(400).json({ success: false });
    });
});

axios.interceptor

import React, { useEffect } from "react";
import axios from "axios";

const checkRequests = (Wrapped) => {
  function CheckRequests(props) {
    useEffect(() => {
      //then이나catch로 처리되기 전에 요청이나 응답을 가로챌 수 있습니다.
      axios.interceptors.response.use(
        function (response) {
          // / 요청을 보내기 전에 수행할 일
          return response;
        },
        function (error) {
          // 오류 요청을 보내기전 수행할 일
          switch (error.response.status) {
            case 400:
              props.history.push("/NotFound");
              break;
            case 403:
              props.history.push("/Forbidden");
              break;
            case 404:
              props.history.push("/NotFound");
              break;
            case 500:
              props.history.push("/InternalServerError");
              break;
            default:
              props.history.push("/NotFound");
              break;
          }
          return Promise.reject(error.response);
        }
      );
    });

    return <Wrapped {...props} />;
  }
  return CheckRequests;
};

export default checkRequests;

vscode error

[0] Server Listening on 5000
[0] MongoDB Connected
[0] The collection exists
[0] node:events:368
[0]       throw er; // Unhandled 'error' event
[0]       ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at new NodeError (node:internal/errors:371:5)
[0]     at ServerResponse.setHeader (node:_http_outgoing:576:11)
[0]     at ServerResponse.header (C:\projectb_back_세미\node_modules\express\lib\response.js:776:10)
[0]     at ServerResponse.send (C:\projectb_back_세미\node_modules\express\lib\response.js:170:12)
[0]     at ServerResponse.json (C:\projectb_back_세미\node_modules\express\lib\response.js:267:15)
[0]     at C:\projectb_back_세미\server\routes\announces.js:353:30
[0]     at C:\projectb_back_세미\node_modules\mongoose\lib\model.js:5074:18
[0]     at processTicksAndRejections (node:internal/process/task_queues:78:11)
[0] Emitted 'error' event on Function instance at:
[0]     at C:\projectb_back_세미\node_modules\mongoose\lib\model.js:5076:15
[0]     at processTicksAndRejections (node:internal/process/task_queues:78:11) {
[0]   code: 'ERR_HTTP_HEADERS_SENT'
[0] }
[1] [HPM] Error occurred while proxying request localhost:3000/api/users/auth to http://localhost:5000/ [ECONNRESET] (https://nodejs.org/api/errors.html#errors_common_system_errors)   
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] [HPM] Error occurred while proxying request localhost:3000/api/users/auth to http://localhost:5000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)

Could you give me some advice?

I got error whether it goes to not found page(error page) or not

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文