How to disable Node.js Express (ejs template engine) errors for production?

When I am on a development server and an error appears, Express sends a trace back.

However, this is not good for production. I don't want anyone to see my trackback.

How do I disable this?

Note. I am using EJS as my templating engine - this might be the reason, not express. When I have an undefined variable in an ejs template, for example, ejs displays a traceback and displays it to the user in a white page.

+3


source to share


2 answers


The latest version of Express uses a smart error handler by default.

In mode, development

it sends the full stack trace back to the browser, and in mode production

, it only sends 500 Internal Server Error

.

To take advantage of this, you must install the NODE_ENV

.

For example, to run an application in production mode:

NODE_ENV=production node application.js

      




But if you don't like this default behavior, you can define your own error handler:

app.use(function(err, req, res, next){
  console.error(err);
  res.status(500);
  res.render('error');
});

      

Please note that the error handler must be the last middleware in the chain, so it must be defined at the bottom of your file application.js

.




If you need more information, see

+8


source


So errors can come from expression or ejs. When:



  • Express error. Use special error handling to override the default behavior. Just don't send back the error. Read about it on the page. Or you can use pre-existing middleware such as errorhandler as Leonidas said to override it.
  • Template error: due to jade / ejs etc. Handle errors again instead of the default to send them to the client. Use a callback and check for errors. If they are not displayed, display an error page instead.

    res.render(your_template, {}, function(err, html) {
        if(err) {
            res.redirect('/error');
        } else {
            res.send(html);
        }
    });
    
          

+3


source







All Articles