I have node 7.8.0 and I have read Node.js Best Practice Exception Handling
Still I can't seem to understand error handling in node.js.
For my http
I have
server.on('error', () => console.log('Here I should be replacing
the Error console.'));
For 404
I have this code
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res) => {
res.status(err.status);
res.render('error');
});
404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.
I would like to use my own error handling and never actually write errors like 404 into the console.
Codes that I tried and don't seem to work.
var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
This is due to expressjs. Expressjs if the env is not equal to the test , the all errors writes to the console.
function logerror(err) {
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
Also http.Server does not have an event named error .
I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here ).
Try this instead:
app.use((err, req, res, next) => {
res.status(err.status);
res.render('error');
});
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.