2011-10-03 4 views
23

Node.js에 다음과 같은 컨트롤러/경로 정의가 있습니다 (Express 및 Mongoose 사용). 사용자가 존재하지 않는 페이지를 요청할 때 오류를 처리하는 가장 적절한 가장 적절한 방법은 무엇입니까?Node.js/Express - 페이지를 찾을 수 없을 때의 렌더링 오류

app.get('/page/:pagetitle', function(req, res) { 
     Page.findOne({ title: req.params.pagetitle}, function(error, page) { 
      res.render('pages/page_show.ejs', 
      { locals: { 
       title: 'ClrTouch | ' + page.title, 
       page:page 
      } 
      }); 
     }); 
    }); 

현재 내 앱이 깨집니다. 내가 그 오류로 아무 것도하지 않기 때문에 나는 성공과 같은 시각으로 전달하고 있다고 생각한다.

TypeError: Cannot read property 'title' of null 

감사합니다.

답변

46

예 : error-pages 예를 확인하십시오. 원칙적으로 앱 경로를 등록한 다음 경로에 매핑되지 않은 다른 모든 요청에 ​​대해 모든 404 핸들러를 등록합니다. 마지막으로 500 핸들러가 다음과 같이 등록됩니다.

// "app.router" positions our routes 
// specifically above the middleware 
// assigned below 

app.use(app.router); 

// Since this is the last non-error-handling 
// middleware use()d, we assume 404, as nothing else 
// responded. 

app.use(function(req, res, next){ 
    // the status option, or res.statusCode = 404 
    // are equivalent, however with the option we 
    // get the "status" local available as well 
    res.render('404', { status: 404, url: req.url }); 
}); 

// error-handling middleware, take the same form 
// as regular middleware, however they require an 
// arity of 4, aka the signature (err, req, res, next). 
// when connect has an error, it will invoke ONLY error-handling 
// middleware. 

// If we were to next() here any remaining non-error-handling 
// middleware would then be executed, or if we next(err) to 
// continue passing the error, only error-handling middleware 
// would remain being executed, however here 
// we simply respond with an error page. 


app.use(function(err, req, res, next){ 
    // we may use properties of the error object 
    // here and next(err) appropriately, or if 
    // we possibly recovered from the error, simply next(). 
    res.render('500', { 
     status: err.status || 500 
    , error: err 
    }); 
}); 
+0

예, 익스프레스 예제를 통과 한 것처럼 느껴집니다. 그러나 이것은 어쨌든 매우 도움이되었습니다. 나는 내 자신의 500.ejs 등을 만들었습니다 ... 뷰에서 그리고 지금은 필요에 따라 렌더링하지만, 내 자신의 오류 메시지도 지정할 수 있습니다. 감사. – tuddy

+1

404 처리로 app.use()를 추가하면 어떤 이유에서든 공용 폴더에있는 모든 경로가 망가집니다. /stylesheets/style.css처럼 내 ejs 템플릿에서 정상적으로 액세스하므로 갑자기 잃어 버리게됩니다. 이것에 대한 제안? – netpoetica

+0

여기서 주어진 예제 앞에 app.use (정적 ....)를 이동하여 내 정적 경로를 깨뜨리는 express app.use() 미들웨어로 문제를 해결할 수있었습니다. – netpoetica

3

Node.JS의 주요 문제점 중 하나는 클린 오류 캐칭이 없다는 것입니다. 기존의 방법은 일반적으로 모든 콜백 함수에 오류가있을 경우, 첫 번째 인수는 null이 아닌 그래서 예를 들면 :

function(error, page){ 
    if(error != null){ 
     showErrorPage(error, req, res); 
     return; 
    } 
    ...Page exists... 
} 

너무 많은 콜백과 함께 잠시 후 추한 얻을 수있는 것, 내가 사용하는 것이 좋습니다 async과 같은 것으로, 오류가 하나있는 경우 직접 오류 콜백으로 이동합니다.

편집 : express error handling을 사용할 수도 있습니다.

+0

+1이 도움이되었습니다. 'null' 대신'undefined'가 없어야합니다. –

+0

@SushantGupta no, ** Nican **이 맞습니다. null이거나 오류 객체가 있습니다. –