Reputation: 5283
I have created one common error handling middleware to handle all the error in the application. but it shows some Error when i run my api like 'Error: Can't set headers after they are sent.' I am manually raising an error by using undefined error 'a' like res.json("testing"+a);
error:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (D:\nodejs\synchronizer\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (D:\nodejs\synchronizer\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\nodejs\synchronizer\node_modules\express\lib\response.js:267:15)
at process.on (D:\nodejs\synchronizer\middlewares\logging.js:31:21)
at emitTwo (events.js:131:20)
at process.emit (events.js:214:7)
at emitPendingUnhandledRejections (internal/process/promises.js:108:22)
at runMicrotasksCallback (internal/process/next_tick.js:124:9)
[nodemon] app crashed - waiting for file changes before starting...
server.js
const express = require('express');
const log = require('../middlewares/logging');
module.exports = function(app){
// default options
app.use(fileUpload());
//it is required for form submit for post method
app.use(express.json());
const bodyParser = require("body-parser");
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
// for parsing application/json
app.use(bodyParser.json());
app.use(bodyParser.text());
// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true }));
//form-urlencoded
// for parsing multipart/form-data
//app.use(upload.array());
//this is middleware is responsible to serve websites static contents of public folder
app.use(express.static('public'));
//Every Request Response Logging Middleware
app.use(log);
app.get('/test', async (req, res) => {
res.json("testing"+a);
});
}
logging.js
const winston = require('winston');
var getLabel = function (callingModule) {
var parts = callingModule.filename.split('/');
return parts[parts.length - 2] + '/' + parts.pop();
};
module.exports = function(req, res, next) {
const logger = winston.createLogger({
levels: winston.config.syslog.levels,
transports: [
new winston.transports.File({
filename: 'Logs/combined.log',
level: 'info'
})
],
exitOnError: false
});
var logmsg = {
'Request IP':req.ip,
'Method':req.method,
'URL':req.originalUrl,
'statusCode':res.statusCode,
'headers':req.headers,
'Time':new Date()
};
process.on('unhandledRejection', (reason, p) => {
logger.error('exception:'+reason);
//below line causes an error
res.status(200).json({
'statuscode': 200,
'message': 'Validation Error',
'responsedata': 'Unhandled Exception Occured'
});
});
logger.log('info', logmsg);
next();
}
Upvotes: 0
Views: 73
Reputation: 203231
You are creating a new logger, and adding a new handler for unhandledRejection
, for every request.
Instead, create a single logger and a single handler. For example:
const winston = require('winston');
// one (module-wide) logger
const logger = winston.createLogger({
levels: winston.config.syslog.levels,
transports: [
new winston.transports.File({
filename: 'Logs/combined.log',
level: 'info'
})
],
exitOnError: false
});
// one (app-wide) handler
process.on('unhandledRejection', (reason, p) => {
logger.error('exception:'+reason);
});
// the logging middleware
module.exports = function(req, res, next) {
const logmsg = {
'Request IP':req.ip,
'Method':req.method,
'URL':req.originalUrl,
'statusCode':res.statusCode,
'headers':req.headers,
'Time':new Date()
};
logger.log('info', logmsg);
next();
}
If you want to handle errors that occur during the request/response cycle, add a proper error handler.
Upvotes: 1