• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

nodejs에서 middleware 처리 방법

25 May 2021

Reading time ~1 minute

nodejs에서 middleware 처리 방법

기존 function에서 오류가 날 경우 봇으로 메시지 발송 기능을 구현 하려고 합니다.

express에서는 middleware를 활용했었는데, 순수한 javascript에서는 어떻게 해야할지 검색을 해보니 Is there a way to add try-catch to every function in Javascript? 를 확인 할 수 있었습니다.

var tcWrapper = function(f) {
    return function() {
        try {
            f.apply(this, arguments);
        } catch(e) {
            customErrorHandler(e)
        }
    }
}

위 예제의 문제는

  1. 결과 값 return 처리가 안되었다.
  2. async (비동기) 처리에서 오류 발생시 catch가 안됩니다.

이를 해결하기 위해서 다음과 같이 해결하였습니다.

// 예제 function
const example = function ({ data }) {
  return new Promise((res, rej) => setTimeout(() => { rej({ status: 100, id: data.id, name: "임광규" }) }, 1000));
}

// middleware 구현
const wrapper = function (f) {
  return async function () {
    try {
      return await f.apply(this, arguments);
    } catch (err) {
      try {
        const { statusCode: status } = JSON.parse(err);
        if (status > 400) {
          console.log("status is over the 400")
        }
      } catch (e) { console.log(e) };

      throw err;
    }
  }
};

// 사용 예제 
(async () => {
  const fnc = wrapper(example);
  const result = await fnc({ data: { id: "23201" } });
  console.log(result)
})();
  1. return 구문 추가로 최종 결과값 전달
  2. async, await 키워드 추가로 비동기에 오류 누락 문제 해결
  3. throw 구문으로 오류 전파

사용은 module.export 시 function을 감싸서 처리 합니다.

module.exports = {
  getUsers: wrapper(getUsers),
}

참고자료

  • Is there a way to add try-catch to every function in Javascript?


nodejsmiddleware Share Tweet +1