next 활용법
undefined인 asdasdad에서 error를 catch해서 그 다음 미들웨어인
res.send('에러났습니다!!!!!!!!!!!!!!!!!!!!!!!')가 보여진다.
app.use(
(req, res, next) => {
console.log('1 모든 요청에 실행하고 싶어요');
next();
},
(req, res, next) => {
try {
console.log('에러 try catch');
console.log(asdasdad);
} catch (err) {
console.log(err);
next(err); // next에 인수가 들어가있으면 error처리 미들웨어로 넘어감.
}
}
);
// 에러처리 미들웨어
app.use((err, req, res, next) => {
console.error(err);
res.send('에러났습니다!!!!!!!!!!!!!!!!!!!!!!!');
});중복을 제거할 수 있다.
if문 안에 true이면 다음 미들웨어인
console.log('예, 물론 실행됩니다.')가 실행되고false라면 바로 아래 미들웨어인
console.log('실행되나요?')가 실행된다. 중복을 줄이기에 용이하다.
Last updated