Reputation: 7226
I am working on a NodeJS module, and I have the following problem:
When some error occurs in the promise chain, I can handle the exception, log it to my centralized logging tool, and all is well.
However, from time to time I see some errors that right out crash the application, and it restarts leaving me with nothing to go on. Only when I look into the logs in the machine that I can figure out what is going on. The latest one was this:
TypeError: Converting circular structure to JSON
How can I log the error that crashes the application to a centralized log tool. I understand that if the app died it can't do anything. But there must be a strategy to do this
Upvotes: 0
Views: 118
Reputation: 30715
You can try a logging library such as Winston with the express-winston module express-winston this provides error logging middleware, for example:
var express = require('express');
var expressWinston = require('express-winston');
var winston = require('winston');
var app = express();
app.use(expressWinston.logger({
transports: [
new winston.transports.File({ filename: 'express.log' })
],
format: winston.format.combine(
winston.format.json()
)
}));
app.get('/test', function(req, res, next) {
res.send('All good');
});
app.get('/error', function(req, res, next) {
// Let's cause an error.
let r = JSON.stringify(req);
});
app.listen(3000, function(){
console.log(`Express Listening on port ${this.address().port}`);
});
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.File({ filename: 'express-error.log' })
],
format: winston.format.combine(
winston.format.json()
)
}));
Upvotes: 0
Reputation: 2353
Best way to handle the exception is to create one helper function where you must configure with error logging tool like (rollbar in heroku), and in every function/routes, you must include your source code inside the try-catch block. Write your code inside the try section and use the helper function and pass the exception to the helper file. It will look like this
//helper.js
const handleException = (exception) => {
//configure your error logging tool here.
}
const internalServerError = env => (err, req, res, next) => {
if (!err) {
return next();
}
handleException(err)//utilize common handler
};
module.exports = { handleException }
and in the main file
//app.js
const { handleException, internalServerError } = required('helper');
app.post((req, res) => {
try {
//your code will goes here
} catch(err) {
handleException(err)//you can customize error as per requirements
}
});
//uncatch exception will trigger here. Put this bottom of the routes file.
app.use(internalServerError());
Upvotes: 1
Reputation: 23848
Place inside try/catch block any expression that might generate an error . Handle the error there or forward it with new information attached.
try {
suspectedFunction()
}
catch(e) {
logError(e)
if (necessary){
e.parseSuccess = false;
throw e
}
}
Upvotes: 0