0.1.0 • Published 6 years ago
@sendyit/http-error-handler v0.1.0
Installation
This Express middleware is available through the npm registry.
Installation is done via the npm install command:
$ npm install @sendyit/http-error-handler
Examples
Error handling without a logger
By default the middleware will log to the console
import express from 'express';
import { httpErrorHandler, httpErrors } from '@sendyit/http-error-handler';
const app = express();
app.use(httpErrorHandler());
app.get('/does-not-exist', () => {
throw new httpErrors.HTTP404Error('Oops!');
});
Error handling with a simple logger
Using a logger without options, the middleware will default to using "warnings" for client errors and "errors" for server errors
import express from 'express';
import winston from 'winston';
import { httpErrorHandler, httpErrors } from '@sendyit/http-error-handler';
const app = express();
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
],
});
app.use(httpErrorHandler(logger));
app.get('/does-not-exist', () => {
throw new httpErrors.HTTP404Error('Oops!');
});
Error handling with logging functions
Logging functions can be used instead of a logger
import express from 'express';
import { httpErrorHandler, httpErrors } from '@sendyit/http-error-handler';
const app = express();
app.use(httpErrorHandler(null, {
clientError: (message) => { console.warn(message) },
serverError: (message) => { console.error(message) }
}));
app.get('/does-not-exist', () => {
throw new httpErrors.HTTP404Error("Oops!");
});
Error handling with a logger that specifies which logging functions to use
Pass a configuration object to the middleware specifying which logger functions to use for the type of error
import express from 'express';
import winston from 'winston';
import { httpErrorHandler, httpErrors } from '@sendyit/http-error-handler';
const app = express();
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
],
});
app.use(httpErrorHandler(logger,
{ clientError: 'warn', serverError: 'error' }));
app.get('/does-not-exist', function (req, res) {
throw new httpErrors.HTTP404Error("Oops!");
});