BackEnd/Express

[Express] Error Handling

Grace 2023. 4. 19. 10:07

다른 미들웨어 함수와 동일한 방법으로 오류 처리 미들웨어 함수를 정의할 수 있지만, 오류 처리 함수는 3개가 아닌 4개의 인수 (err, req, res, next)를 갖습니다.

app.use((err, req, res, next) => {
  console.error(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((err, req, res, next) => {
  // logic
})

미들웨어 함수 내부로부터의 응답은 HTML 오류 페이지, 단순한 메시지 또는 JSON 문자열 등의 형식일 수 있습니다.

조직적 혹은 상위 레벨 프레임워크 목적을 위해, 여러 오류 처리 미들웨어 함수를 정의할 수 있으며, 일반적인 미들웨어 함수를 정의할 때와 매우 비슷합니다.

미들웨어는 순차적으로 실행되기 때문에, 해당 미들웨어를 만났다는 것은 이전 미들웨어들에 대응하는 요청을 처리하지 못했다는 것을 뜻하므로 마지막에 선언해줍니다.

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

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

https://yohanpro.com/posts/nodejs/error-handling

'BackEnd > Express' 카테고리의 다른 글

[Express] req, res 객체  (0) 2023.04.19
[Express] middleware  (0) 2023.04.19
[Express] 라우팅  (0) 2023.04.19