Skip to content

Instantly share code, notes, and snippets.

@Raynos
Last active August 29, 2015 14:05
Show Gist options
  • Save Raynos/91cab673906aebd04eac to your computer and use it in GitHub Desktop.
Save Raynos/91cab673906aebd04eac to your computer and use it in GitHub Desktop.
var STATUS_CODES = require('http').STATUS_CODES;
var sendJson = require('send-data/json');
var url = require('url');
function (req, res, opts) {
var clients = opts.clients;
var config = opts.config;
var errOpts = {
// verbose is true in dev where it prints stacks
// when verbose is false it wont print stacks
verbose: config.get('playdoh-api.error.verbose') || false
};
return defaultErrorHandler;
/*
type TypedError : {
message: String,
statusCode?: Number,
type?: String,
stack?: String,
expected?: Boolean,
messages?: Array<String>
}
defaultErrorHandler : (err?: TypedError)
*/
function defaultErrorHandler(err) {
var parsedUrl = url.parse(req.url);
var statsdKey = 'playdoh-api.error-handler.' +
parsedUrl.pathname;
if (err) {
if (typeof err.expected === 'string') {
if (clients.statsd) {
clients.statsd.increment(statsdKey + '.expected');
}
sendExpectedError(req, res, err, errOpts);
} else {
clients.logger.error('unexpected error', err);
if (clients.statsd) {
clients.statsd.increment(statsdKey + '.unexpected');
}
sendUnexpectedError(req, res, err, errOpts);
}
} else if (clients.statsd) {
clients.statsd.increment(statsdKey + '.ok');
}
}
}
function sendExpectedError(req, res, err, opts) {
var statusCode = err.statusCode || 500;
var body = {
message: err.message || STATUS_CODES[statusCode] ||
STATUS_CODES[500]
};
if (typeof err.type === 'string') {
body.type = err.type;
}
if (Array.isArray(err.messages)) {
body.messages = err.messages;
}
if (opts.verbose) {
body.stack = err.stack;
body.expected = err.expected;
}
sendJson(req, res, {
statusCode: statusCode,
body: body
});
}
function sendUnexpectedError(req, res, err, opts) {
var statusCode = err.statusCode || 500;
var body = {
message: STATUS_CODES[statusCode] ||
STATUS_CODES[500]
};
if (opts.verbose) {
body.message = err.message || body.message;
body.stack = err.stack;
body.expected = err.expected;
}
sendJson(req, res, {
statusCode: statusCode,
body: body
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment