본문으로 바로가기
 

Express FAQ

FAQ How should I structure my application? There is no definitive answer to this question. The answer depends on the scale of your application and the team that is involved. To be as flexible as possible, Express makes no assumptions in terms of structure.

expressjs.com

 

 

라우터를 다 찾았는데도 요청한 내용이 없다면 서버가 죽는다. 때문에 404를 처리하는 미들웨어(라우터)를 만들어야 한다. (이 포스팅의 주제와는 관련 없지만 기억하자. 라우터도 미들웨어다!)

 

일반적인 app.js의 구성 순서에 따라 마지막에 404와 에러 핸들러를 만들어보자. 만약 express-generator로 생성했다면 이미 기본적으로 구성되어 있을 것이다.

 

 

 

 

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

 

404 응답은 에러의 결과물이 아닙니다. 따라서 에러 핸들 미들웨어는 404를 capture하지 못할 것입니다. 404는 그냥 단순히 무엇을 반환해야 할 것인가가 정해지 있지 않다는 것입니다. 

// 404 NOT FOUND
app.use((req, res, next) => {
  res.status(404).send("DAMN! 404 NOT FOUND... YOU MAD?");
});

 

 

 

Error

 

다음과 같은 컨트롤러가 있다고 가정하면, 에러가 발생할 때 next(err)로 넘겨주면 됩니다.

export const postCreateMovie = async (req, res, next) => {
  const { title, year, rating, synopsis, genres } = req.body;

  const genresList = genres.split(",");
  await Movie.create({
    title,
    year: Number(year),
    rating: Number(rating),
    synopsis,
    genres: genresList,
  })
    .then((res) => {
      console.log(res);
      res.render("create.pug");
    })
    .catch((err) => {
      next(err);
    });
};

 

next(err)로 에러를 넘기면 곧장 에러를 처리하는 미들웨어로 이동합니다. 모든 라우터 중 최하단에 둬야겠죠? app.js와 같은 메인이 되는 곳에 맨 아래에 위치시키면 되겠죠.

// Error handling
app.use((err, req, res, next) => {
  console.log(err);
  res.status(500).send("Server Error");
});

 

 

🎈 res.send() 와 res.status(200).send()
둘 사이에는 차이가 없다. 기본적으로 성공적인 접근은 status 코드를 200을 보내기 때문에 생략했지만 express 5버전 부터는 status을 생략할 수 없게 만든다는 이야기가 있다.

 

 

김정환님의 블로그에서 견고한 express 에러 처리에 대한 글을 쓰셨으니 참고해보자

http://jeonghwan-kim.github.io/node/2017/08/17/express-error-handling.html

 

에러 처리를 위한 익스프레스 가이드

원문: http://thecodebarbarian.com/80-20-guide-to-express-error-handling.html

jeonghwan-kim.github.io


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체