nodejs에서 try/catch문을 사용하여 에러가 발생했을 때 서버가 종료되는 것을 막을 수 있다.
또한 AsyncHandler를 사용하여 코드를 더 간소화하고 반복되는 코드를 줄일 수 있다.
function someAsyncFunction(){
return "test";
}
router.get('/example', async (req, res, next) => {
const result = await someAsyncFunction();
res.status(200).json(result);
});
test를 응답하는 API가 있을 때
평상시엔 잘 조회를 해 오지만 에러가 발생하면?
function someAsyncFunction(){
throw new Error;
return "test";
}
router.get('/example', async (req, res, next) => {
const result = await someAsyncFunction();
res.status(200).json(result);
});
이렇게 에러를 처리하지 못하고 서버가 종료되어 버린다.
function someAsyncFunction(){
throw new Error;
return "test";
}
router.get('/example', async (req, res, next) => {
try {
const result = await someAsyncFunction();
res.status(200).json(result);
} catch (error) {
next(error);
}
});
예외처리를 해놓은 부분으로 넘어가 500에러를 발생 시키지만 서버는 종료되지 않는다.
하지만 모든 API 코드에 try/catch문을 일일히 사용하여 예외처리를 하는건 반복되는 코드가 많아 불편하고 보기에도 좋지않다. 이럴때 AsyncHandler로 따로 코드를 빼내어 사용한다.
module.exports = (reqHandler)=>{
return async(req, res, next)=>{
try{
await reqHandler(req,res)
}catch(err){
next(err);
}
}
}
이렇게 AsyncHandler라는 모듈을 만들어주고 가져와준다.
function someAsyncFunction(){
throw new Error;
return "test";
}
router.get('/example', asyncHandler(async (req, res) => {
const result = await someAsyncFunction();
res.status(200).json(result);
}));
AsyncHandler를 사용하여 훨씬 깔끔하고 적은코드로 예외처리를 할 수 있다.