Skip to content

Commit

Permalink
Export a helper function that supports creating instances by status c…
Browse files Browse the repository at this point in the history
…ode with a fallback to an Unknown class.
  • Loading branch information
papandreou committed Sep 9, 2014
1 parent c6b0672 commit 3669d93
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Usage

var httpErrors = require('httperrors');

// Instatiate by status code:
var myError = httpErrors(412);

// Instantiate by name (UpperCamelCase):
var err = new httpErrors.NotFound('The thing you were looking for was not found');

Expand Down
12 changes: 11 additions & 1 deletion lib/httpErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,17 @@ var httpErrorNameByStatusCode = {
511: 'Network Authentication Required' // RFC 6585
};

var httpErrors = module.exports = {};
var httpErrors = module.exports = function (options) {
if (typeof options === 'undefined') {
options = {};
} else if (typeof options === 'number') {
options = {statusCode: options};
}
options.status = options.statusCode;
return (httpErrors[options.statusCode] || httpErrors.Unknown)(options);
};

httpErrors.Unknown = createError({name: 'Unknown'});

/// Map the error codes/names, as defined in Node's [http
/// module](http://nodejs.org/docs/latest/api/http.html).
Expand Down
26 changes: 26 additions & 0 deletions test/httpErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,30 @@ describe('httpErrors', function () {
expect(err.message, 'to equal', 'foo');
expect(err.url, 'to equal', 'bar');
});

describe('when invoked as a function', function () {
it('should create an instance of httpErrors.Unknown if called with no arguments', function () {
expect(httpErrors().name, 'to equal', 'Unknown');
});

describe('and passed a number', function () {
it('should create an instance of the proper error for a known status code', function () {
expect(httpErrors(412).name, 'to equal', 'PreconditionFailed');
});

it('should create an instance of httpErrors.Unknown if given a status code that is not directly supported', function () {
expect(httpErrors(595).name, 'to equal', 'Unknown');
});
});

describe('and passed an options object', function () {
it('should create an instance of httpErrors.Unknown if the status code is not directly supported', function () {
expect(httpErrors({statusCode: 595}).name, 'to equal', 'Unknown');
});

it('should create an instance of httpErrors.Unknown if no status code is provided', function () {
expect(httpErrors({foo: 'bar'}).name, 'to equal', 'Unknown');
});
});
});
});

0 comments on commit 3669d93

Please sign in to comment.