본문 바로가기

BACKEND

[Express.js] 에러 핸들링

Error handling 오류처리 미들웨어 함수

오류처리함수(오류 처리 미들웨어)는 3개가 아닌 4개의 인수를 갖는다.

app.use(function(err, req, res, next) {
  console.log(err.stack);
  res.status(500).send("Something broke!");
});

 

다른 app.use() 및 라우트 호출을 정의한 후에 마지막으로 정의해야 한다.

const bodyParser = require("body-parser");
const methodOverride = require("method-override");

app.use(bodyParser());
app.use(methodOverride());
app.use(function(err, req, res, next) {
  // logic
});

 

next() 함수에 인자가 있는 경우는 (’route’ 제외) 인자가 4개 등록되어있는 함수 즉, 오류 처리 함수를 실행하도록 약속되어있다. Express 공식문서에 따르면 404 응답은 오류로 인해 발생하는 결과가 아니며 오류 핸들러 미들웨어는 이를 오류로 파악하지 않는다. 404 응답은 단순히 실행해야 할 추가적인 작업이 없다는 것, 즉 Express는 모든 미들웨어 함수 및 라우트를 실행했으며 이들 중 어느 것도 응답하지 않았다는 것을 나타낼 뿐이다. 404 응답을 처리하기 위해서는 해당 미들웨어 함수를 스택의 가장 아래(다른 모든 함수의 아래)에 추가하기만 하면 된다.

app.use(function(req, res, next) {
  res.status(404).send("Sorry cant find that!");
});

 

Reference

https://expressjs.com/ko/

 

Express - Node.js 웹 애플리케이션 프레임워크

Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크 $ npm install express --save

expressjs.com

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

 

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

 

'BACKEND' 카테고리의 다른 글

Node.js와 Express.js  (0) 2022.08.19
[Express.js] res.json vs res.send vs res.end  (0) 2022.08.19
[Express.js] 미들웨어  (0) 2022.08.19