3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2023년 1월 29일 22:24 #64844
이수인참가자안녕하세요, nodejs 강의를 수강하고 있는 수강생입니다. 강의를 보면서 궁금한 점이 생겨서 문의 남깁니다. "쇼핑몰처럼 상세페이지를 만들어보자 (URL parameter)"에서 마지막 부분에 존재하지 않는 페이지 접속시에 에러를 띄우는 것을 스스로 해보라고 해서 계속 시도해보고 구글링을 해도 해결이 되지 않습니다. app.get('/detail/:id', function(요청, 응답){ db.collection('post').findOne( { _id : parseInt(요청.params.id) }, function(에러, 결과){ console.log(에러);//=>null if(에러){ 응답.status(500).send('500!!'); }else{ console.log(결과); 응답.render('detail.ejs', { data : 결과 }); } }) }) 우선 이건 js 파일이고 <div class="container mt-3"> <h4 class = "text-center">Detail Page</h4> <div class="card" style="width: 100%"> <div class="card-body"> <h5 class="card-title"><%= data.제목 %></h5> <h6 class="card-subtitle mb-2 text-muted"><%= data.날짜 %></h6> <p class="card-text">임시내용입니다.</p> edit </div> </div> </div> 이건 detail 파일입니다. detail/90은 없어서 detail/90에 접속하면, if문에 걸려서 500 error가 띄워질 거라고 생각했습니다.(웹페이지 콘솔창에 500 에러가 떠서 500 error로 코드를 짰습니다.) 그런데 console.log(에러)를 하면 null이 출력되고, if문을 통과를 해버립니다. 터미널을 보면 이런 출력이 뜹니다.
20| <div class="card" style="width: 100%"> 21| <div class="card-body"> >> 22| <h5 class="card-title"><%= data.제목 %></h5> 23| <h6 class="card-subtitle mb-2 text-muted"><%= data.날짜 %></h6> 24| <p class="card-text">임시내용입니다.</p> 25| edit
Cannot read property '제목' of null at eval (eval at compile (/workspace/coding_apple/node_modules/ejs/lib/ejs.js:673:12), <anonymous>:15:31) at detail (/workspace/coding_apple/node_modules/ejs/lib/ejs.js:703:17) at tryHandleCache (/workspace/coding_apple/node_modules/ejs/lib/ejs.js:274:36) at View.exports.renderFile [as engine] (/workspace/coding_apple/node_modules/ejs/lib/ejs.js:491:10) at View.render (/workspace/coding_apple/node_modules/express/lib/view.js:135:8) at tryRender (/workspace/coding_apple/node_modules/express/lib/application.js:657:10) at Function.render (/workspace/coding_apple/node_modules/express/lib/application.js:609:3) at ServerResponse.render (/workspace/coding_apple/node_modules/express/lib/response.js:1039:7) 이 방법이 안돼서 구글링 해보니, 미들웨어로 핸들링을 하라는 글을 봤습니다. 그래서 js 코드 맨 마지막에
// app.use(function(req, res, next) { // res.status(404).render('404 error page!'); // })
// app.use(function (err, req, res, next) { // console.error(err.stack) // res.status(500).send('500 error page!') // }); 위 코드를 추가하니, 정상적으로 웹페이지에 "500 error page!"가 뜹니다.
1. 미들웨어로 핸들링 하는 것 말고 function 내에서 if문으로 에러를 처리하려면 어떻게 해야 되나요? 2. 404 에러와 500에러 외에도 여러에러가 있을 텐데 여러가지 에러들을 미들웨어로 처리하려면 어떻게 코드를 짜야하나요? 위 코드같은 순서가 맞나요?
3. 404 에러와 500에러의 parameter가 다른데, 두 코드의 차이는 무엇인가요?
2023년 1월 30일 09:44 #64885
codingapple키 마스터에러는 DB시스템의 에러 이런거라 결과가 비었는지 안비었는지로 체크합시다 순서는 상관없습니다 파라미터4개 넣으면 에러핸들링용 미들웨어가됩니다
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.