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
http://thecodebarbarian.com/80-20-guide-to-express-error-handling.html
'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 |