Nodo.js / Express - Error de renderizado cuando no se encontró la página


Tengo la siguiente definición de controlador/ruta en Node.js (usando Express y Mangosta). ¿Cuál sería la forma más adecuada para manejar el error cuando el usuario solicita una página que no existe?

  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
            }
          });
      });
  });

Actualmente rompe mi aplicación. Creo que porque no estoy haciendo nada con el error solo estoy pasando a la vista como un éxito?

TypeError: Cannot read property 'title' of null

Muchas Gracias.

Author: Matt, 2011-10-04

2 answers

Echa un vistazo al ejemplo de error-pages de express. El principio es registrar las rutas de su aplicación primero, luego registra un controlador catch all 404 para todas las demás solicitudes que no se asignan a una ruta. Finalmente, se registra un manejador 500, de la siguiente manera:

// "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
  });
});
 47
Author: blockchaindev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-17 09:10:38

Uno de los principales problemas con Node.JS es que no hay una captura de errores limpia. La forma convencional suele ser para cada función callback, el primer argumento es el not null si hay un error, así por ejemplo:

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

Las cosas pueden ponerse feas después de un tiempo con demasiadas devoluciones de llamada, y recomiendo usar algo como async, de modo que si hay un error, vaya directamente a una devolución de llamada de error.

EDIT: También puede usar express error handling.

 3
Author: Nican,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-07 22:25:31