참고)
https://cheony-y.tistory.com/198
에러 처리 미들웨어
매개변수가 err, req, res, next로 네 가지가 필요하다.
console.log(err)를 통해 콘솔에서 에러를 확인할 수 있고 브라우저에서는 '에러가 났다'만 보여진다.
app.use((error, req, res, next) => {
console.log(error);
res
.status(error.status || 500)
.send({'에러가 났다'});
});
미들웨어를 통해 에러처리
app.use((req, res, next) => {
res.status(404).send('404 에러처리');
});
오류 클래스 만들어서 오류 처리하기
Error 클래스를 상속받아서 오류 클래스를 작성을 한다.
에러 코드, 메세지, 이름 정의.
class MethodNotAllowed extends Error {
status = 405;
constructor(message = '사용할 수 없는 메소드입니다.') {
super(message);
this.name = 'Method Not Allowed';
}
}
module.exports = MethodNotAllowed;
존재하지 않는 경로로 요청이 들어왔을 때 보여주는 오류
const MethodNotAllowed = require('./error/methodNotAllowed');
app.all('*', (res, req) => {
throw new MethodNotAllowed();
});
'개발 > Node.js' 카테고리의 다른 글
ORM에 대하여 (0) | 2023.09.21 |
---|---|
node + postgreSQL + Sequelize (0) | 2023.09.20 |
Node 프레임워크 14가지 (0) | 2023.08.18 |
페이지네이션 (0) | 2023.08.04 |
Json Web Token 이란? (0) | 2023.08.03 |