'Error handling globally using axios intercpetor

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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source