0.1.7 • Published 7 years ago
http-server-request-handlers-error-logger v0.1.7
http-server-request-handlers-error-logger
an http.Server request handler for express that handles IncomingMessage errors
table of contents
notes
this middleware should be added after all “non-error” middleware in the application.
it expects the following:
reqis an objectreq.headersexistsreq.connectionexistsresis an objectres.getis a functionres.sendis a function
it implements the following:
- creates an error object containing the following properties
{
error: {
body: req.body || null,
code: err.code || null,
date: new Date(),
errorCode: err.errorCode || null,
headers: req.headers || null,
message: err.toString() || null,
method: req.method || null,
originalUrl: req.originalUrl || null,
remoteAddress: req.headers[ 'x-forwarded-for' ] || req.headers[ 'x-real-ip' ] || req.connection.remoteAddress || null,
session: req.session || null,
status: err.status || null,
statusCode: err.statusCode || 500
}
}- adds the error
statusCodetoresasres.statusCode - logs the error object to
console.error - logs the
err.stacktoconsole.errorif theerror.statusCodeis not equal to404 - creates a message format based on the current request
content-typeand server environment- when the response
content-typeisapplication/jsonerror: { code: err.code || null, errorCode: err.errorCode || null, message: err.toString(), status: err.status || null, statusCode: err.statusCode || 500 } - when
NODE_ENVis set todevelopmentandcontent-typeis notapplication/json- the
err.stack
- the
- otherwise the
err.message
- when the response
installation
npm install http-server-request-handlers-error-loggerapi
/*
* @param {Error} err
* @param {number} err.status
* @param {number} err.statusCode
*
* @param {IncomingMessage} req
*
* @param {ServerResponse} res
* @param {Function} res.send
*
* @returns {undefined}
*/
function errorLogger( err, req, res )use
var express = require( 'express' );
var app = express();
var errorLogger = require( 'http-server-request-handlers-error-logger' );
// ... middleware declarations
// ... route declarations
app.use( errorLogger );