error handler 와 router, middleware의 비교

node js 에서는 기본적으로 error handler 를 제공한다.

app.use((err, req, res, next) => {
 
})

그리고 err 인자가 없는 경우 미들웨어로 간주된다.

app.use((req, res, next) => {
 
})

그리고 아래의 경우에는 라우터로 간주된다. 경로와 http method가 지정되어 있다.

app.get('/', (req, res, next) => {
 
});

error handler 는 다른 미들웨어와 라우터 호출을 정의한 후 마지막으로 정의해야 한다.

즉, 순서에 영향을 받는다.

// router
app.get('/', (req, res, next) => {
  next();
});
 
// error handler
app.use((err, req, res, next) => {
 
});
 
app.listen(3000, function() {
 
});

next(err) 를 호출할 경우 중간에 등록된 미들웨어를 건너 뛰고 error handler 부분으로 건너가게 된다.

즉 next 인자로 new Error() 객체를 보내든 string 값을 보내면 에러로 감지하여 error handler로 보낸다.

// A router
app.use((req, res, next) => {
  // next(new Error('error message'))
  next('error message');
});
 
// B router - skip
app.use((req, res, next) => {
  console.log('B router');
});
 
// error handler
app.use((err, req, res, next) => {
  // print: error message
  console.log(err);
});

next() 혹은 next('route') 호출시 다음 미들웨어 혹은 라우터로 흐름을 넘긴다.

아래 예제는 /users/0 로 접근한 경우 next('route')를 통해 다음 라우터로 전달하게 된다.

/users/1 로 접근한 경우 next()를 통해 다음 미들웨어로 흐름을 넘겨 'next() call' 이 출력된다.

아래 예제는 router handler를 통해 하나의 경로에 2개의 route를 설정한 경우이다.

app.get('/users/:id', ( req, res, next) => {
  if(req.params.id == 0) next('route')
  else next()
}, (req, res, next) => {
  res.send('next() call')
});
 
app.get('/users/:id', ( req, res, next) => {
  res.send("next('route') call")
})

정리

error handler 에 대해 알아보았다. 개발을 하다보면 에러 처리를 하는 법이 아니라 어떻게 하는게 좋은지에 대한 best practice에 대해 궁금하게 된다.

블로그를 찾던 중 error handler에 대한 best practice 내용이 담겨 있다. 나중에 한번 보길 바란다.

https://www.joyent.com/node-js/production/design/errors

'Framework > Nodejs' 카테고리의 다른 글

express-session  (0) 2018.01.03
pm2에 대해 알아보자  (0) 2017.10.06
[마이크로서비스] 세네카와 익스프레스 연동  (0) 2017.10.02
[마이크로서비스] Seneca  (0) 2017.10.02
비동기와 CPU Bound  (0) 2017.09.04

+ Recent posts