简体   繁体   中英

Error handeling when file is not found in nodeJS and Express framework

I want to display multiple html/jade files using node/express.

I'm trying to create a basic rule for handeling non-existing files.

If I would write this code I will not handle error responses but it will work:

app.get('/art/:project', function(req, res){
        var project = req.param('project');
        res.render('art/' + project);
    });

if I'm writing this code it will handle error correctly but for some reason will not display the page when the file DO exist.

 app.get('/art/:project', function(req, res){
        var project = req.param('project');
        res.render('art/' + project, function(err, html) {
          if (err) {
            res.redirect('/');
         }
       });
    });

What am I missing?

I've found out that this will work but it seems extremely un-efficient:

  res.render('art/' + project, function(err, html) {
    console.log(err, html);
    if (err) {
        res.redirect('/');
    } else {
        res.render('art/' + project);
    }
  });

Isn't it better to check if the file exists before to try to render it.

var fs = require('fs');

app.get('/art/:project', function(req, res){
    var project = req.param('project');
    fs.exists('art/' + project + '.jade', function(exists) {
        if (exists) {
            res.render('art/' + project);
        } else {
            res.redirect('/');
        }
    });
});

Well check its existence is OK but the doc suggests:

fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

So it's better to catch exception then handle it:

try {
    res.render('art/' + project);
} 
catch(e) {
    if (e.code === 'ENOENT')
        res.redirect('/');
    else
        throw e;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM