Remove nodejs error dump - node.js

everytime I have a critical error which terminates the server on NodeJS which comes from a request of a client, he gets the error dump.
How can I change this behaviour ?

I assume you are talking about Express.js. Error stack trace is sent to client when environment is not production (please refer Express docs).
To disable this behavior, you should set NODE_ENV environmental variable
to production.

You can process the error - more common is 404 and 500.
Follow one example to do this (in case express):
exports.notFound = function(req, res, next) {
res.status(404);
res.render('not-found');
};
exports.serverError = function(error, req, res, next) {
res.status(500);
res.render('server-error', {error: error});
};
And create the files not-found and server-error (EJS or Jade for example) for show custom page in case of error.

Related

ExpressJS breaking when trying to serve missing images

ExpressJS Newbie Warning
I have a simple server running with expressjs and all works well when all images are present. But if an image is missing expressjs stops with the following error
(node:5793) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Cannot find module 'jpg'
This is preventing anything else from loading, or even an links working. The page just hangs there. Shouldn't it simple not serve the image (send a 404) and still allow the site to work?
UPDATE
router.get('/*', (req, res, next) => {
dynamicStatic.setPath(path.resolve(__dirname, 'public/templates/' +
app.get('templatePath')));
res.render('index');
});
I use dynamicStatic because I need to be able to set the path dynamically based on some conditions. This sets express.static under the hood. I don't think that has anything to do with it because other images are being served fine. Of course I could be wrong, though.
UPDATE 2
The images remain in a (pending) state which is where the hang up is coming from.
This image shows the error messages I receive in Node/Express.
I think catching the exception with a try {} catch block should do the job just fine.
Put the code that could throw an exception in the try block and if an exception is thrown send the 404 status.
Here’s a try:
router.get('/*', (req, res, next) => {
try {
dynamicStatic.setPath(path.resolve(__dirname, 'public/templates/' +
app.get('templatePath')));
res.render('index');
} catch(err) {
res.sendStatus(404);
}
});

too many redirects in express

I want to handle all my cookies and session stuff in a function then redirect to the destination path. I use this function in Express:
app.all('*', function(req, res, next){
if('_id' in req.session)
next()
else if('userInfo' in req.cookies){
req.session._id = req.cookies.userInfo._id
next()
} else {
res.redirect('../login')
}
res.end()
})
but browser print this error:
net::ERR_TOO_MANY_REDIRECTS
what's the problem?
This error occurs when a web browser is redirecting you to another web page which then that web page redirects you back to the same browser again. Your configurations are wrong. app.all('*', ..) runs again and again whenever a request is made, which causing repetition.
You need to have better configurations than app.all(*..) //all. You need to specify it more so that it doesn't repeat itself.
I would say limit it down to some urls and not all of them. You could do
app.get('/cookieCheckerPage', function(req, res){
//code here
});
Also please see Error 310 (net::ERR_TOO_MANY_REDIRECTS):

Hiding error message in Node.js&Express from POST access

I'm running a Restful API Server based on Node.js using Express.js.
Today, I realized that someone can get information of error of my source code, including directory path of my server, when he send request using Curl like curl -X POST ~.
Error message I get:
TypeError: Cannot read property 'text' of undefined
at exports.list (/usr/local/node/XXX/routes/message.js:49:36)
at callbacks (/usr/local/node/XXX/node_modules/express/lib/router/index.js:124:37)
at param (/usr/local/node/XXX/node_modules/express/lib/router/index.js:118:11)
at param (/usr/local/node/XXXv/node_modules/express/lib/router/index.js:125:11)
How can I hide those critical information when the server displays errors?
I'd set the NODE_ENV flag to production, as the Express.JS doesn't send the stack data in this mode. I recommend you to check out the dotenv module in npm.
If you pass an error to next() and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.
https://expressjs.com/en/guide/error-handling.html
Set your environment variable NODE_ENV to production when running Node.js to suppress stack traces. It’ll still be shown on the console.
You can create a middleware that deals with all unhandled errors for you.
app.use((err, req, res, next) => {
if (err) {
return res.sendStatus(500);
}
next();
});
That will return a 500 Internal Server Error status code to any user creating such an error. Remember to put this at the end of your middleware chain.
Just send them this kind of response if you don't want to send any message
res.sendStatus(500);
or you can use errorhandler in your express setting like this if you want to send stacktrace as well
var errorHandler = require('errorhandler');
.....//define app as express object
if (process.env.NODE_ENV === 'development') {
// only use in development
app.use(errorhandler())
}

Passing errors to client in express

How do you pass nice error messages to clients in express?
app.use(errorHandler);
function errorHandler(err, req, res, next) {
res.send(err);
}
app.post('/login', usernameIsValid, pwdIsValid, createToken);
In usernameIsValid I create a new Error with a message and status and call next(err). Now this bypasses pwdIsValid and createToken like it should BUT the weird thing is my errorHandler logs the error without a console.log. Am I using the default error handler in express somewhere? How do I turn it off? I have tried both production and development for NODE_ENV.
On the client xhr.responseText is my error.message + what looks like a stack trace? I've even tried just to send err.message but it looks the same.
One way to handle this mess is to make each middleware (if there is an error) create an error string like req.data.err = "invalid username" and then make sure each following middleware checks req.data.err if the string is present. But this is tedious as hell >_<
I solved it. You need to apply the error handler app.use(errorHandler) dead last after all other routes. This disables the built-in error handler. Now you may pass pretty error messages to the client.
Read more here.
edit: process.env.NODE_ENV does not matter.
From the express documentation site
If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.
So if you want to avoid the stacktrace you only need to execute your application with the NODE_ENV set to production.
Run you application as follows:
$ NODE_ENV=production node file.js

Node.js and Express not working?

I am currently trying to learn implementing RESTful APIs using Node.js & Express. Using this tutorial: http://code.runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4
I created each file on my local drive and tried running the code using node server.js..However I kept on getting an error. Why might be causing this?
The code you chose to run is only routing requests for urls that begin with /api as you can see here:
app.use('/api', router);
On top of that, the routes it accepts are /players and /player/:id:
router.get('/players', function(req, res, next) {
res.json({ players: players.getAllPlayer() });
});
router.get('/players/:id', function(req, res, next) {
var player = players.getPlayerById(req.params.id)
res.json(player);
});
For every request, including the routes above, it outputs the method and url to console.log.
Even when it fails to get /, you should see GET / in your console.
Now try to access this url: 0.0.0.0:8080/api/players
It works, right?

Resources