- async 함수에서 발생한 오류는 async 함수안에서 호출 된 또다른 asynce 함수의 try/catch로 예외처리가 가능
-> wrapping함수 구현
const wrapAsync = asyncFn => {
if (asyncFn.length <= 3) {
return (async (req, res, next) => {
try {
return await asyncFn(req, res, next)
} catch (error) {
return next(error)
}
})
}
else {
return (async (err, req, res, next) => {
try {
return await asyncFn(err, req, res, next)
} catch (error) {
return next(error)
}
})
};
};
module.exports = wrapAsync;
- try-catch를 이용해 상위 래퍼 메소드에서 에러 핸들링을 해주기 때문에 모든 메소드에 try-catch를 사용할 필요x
- async — await가 필요한 부분에만 wrapwrapAsync 메소드를 사용
-사용예시
//routing middleware
const fakeWait = () => new Promise((resolve) => setTimeout(resolve, 100));
async function asyncRoute(req, res) {
await fakeWait();
res.send({ ok: true });
}
router.get('/async', wrapAsync(asyncRoute));
//error handling
app.use((err, req, res, next) => {
res.status(500);
res.json({
error: err.message,
});
});
참고
'Javascript > express' 카테고리의 다른 글
express(4) : JWT를 통한 회원 인증 시스템 구현 (0) | 2019.09.17 |
---|---|
express (3) : handling mongoDB (0) | 2019.09.05 |
express (2) : 요청과 응답, 쿠키와 세션, REST API와 라우팅 (0) | 2019.09.05 |
express (1) : 웹서버 생성, 미들웨어, 라우팅 (0) | 2019.09.05 |