320x100
320x100

미들웨어에서의 에러 핸들링의 중요성

app.get('/User', async function(req, res) {
  let users;
  try {
    users = await db.collection('User').find().toArray();
  } catch (error) {
    res.status(500).json({ error: error.toString() });
  }
  res.json({ users });
});

: 모든 라우터를 위와 같이 작성했을때, status 코드가 바뀌면 모든 라우터를 찾아서 바꿔줘야한다

: 그리고 중복된 코드가 많아지기 때문에 코드를 유지보수하기 힘들다

 

 

 

 

 

wrapAsync 함수의 사용

const app = require('express')();

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  // Async error!
  throw new Error('woops');
}));

app.listen(3000);

function wrapAsync(fn) {
  return (req, res, next) => {
      try {
        await fn();
        next();
      } catch (e) {
        console.log(e);
        res.status(500);
        next();
      }
    // Make sure to `.catch()` any errors and pass them along to the `next()`
    // middleware in the chain, in this case the error handler.
    // fn(req, res, next).catch(next);
  };
}

: 미들웨어에서 사용할 wrapAsync라는 일종의 wrap 함수를 만들고 이를 미들웨어에서 실행할 함수를 파라미터로 호출하여 모든 미들웨어에서 오류가 발생해도 서버가 종료되지 않게 할 수 있음

: wrapAsync 함수내에서는 파라미터로 들어온 함수를 호출하고 try catch 혹은 .catch 등으로 예외처리를 수행

: 모든 미들웨어에서 위와 같이 구성하면 쉽게 API에 대한 에러 핸들링을 할 수 있음

 

 

 

 

Reference

 

The 80/20 Guide to Express Error Handling

Express' error handling middleware is a powerful tool for consolidating your HTTP error response logic. Odds are, if you've written Express code you've written code that looks like what you see below. app.get('/User', async function(req, res) { let users;

thecodebarbarian.com

 

300x250
728x90

'Programming > NodeJS' 카테고리의 다른 글

NodeJS 란?  (0) 2023.06.05
NodeJS 백로그 관리  (0) 2023.05.15
express의 구조  (0) 2023.02.13
NodeJS와 메모리 2 - 가상메모리와 힙 / 스택  (0) 2022.09.12
NodeJS와 메모리 1 - V8 엔진  (0) 2022.09.12