-
nodejs에서 middleware 처리 방법NodeJS 2021. 7. 13. 00:06728x90
기존 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) } } }
위 예제의 문제는
- 결과 값 return 처리가 안되었다.
- 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) })();
- return 구문 추가로 최종 결과값 전달
- async, await 키워드 추가로 비동기에 오류 누락 문제 해결
- throw 구문으로 오류 전파
사용은
module.export
시function을 감싸서 처리
합니다.module.exports = { getUsers: wrapper(getUsers), }
참고자료
728x90'NodeJS' 카테고리의 다른 글
nestjs에서 jest를 이용한 End2End 테스트 케이스를 작성 (0) 2021.07.23 NestJS에서는 기본적으로 jest 기반의 테스트 케이스를 제공합니다. (0) 2021.07.15 [개인프로젝트] Workplace Export (0) 2021.02.20 [개인프로젝트]md5-lite (0) 2021.02.18 MSSQL POOL을 Express 환경에서 사용하기 (0) 2021.02.14