-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (47 loc) · 1.87 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var httpStatusCodes = require('http').STATUS_CODES;
var util = require('util');
var camelCase = require('lodash.camelcase');
var capitalize = require('lodash.capitalize');
/**
* @param {Number} [statusCode=500]
* @param {String|Object} [messageOrProperties]
* @param {Object} [properties]
*/
function HttpError(statusCode, messageOrProperties, properties) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
statusCode = statusCode || 500;
properties = properties || {};
if (messageOrProperties instanceof Object) {
properties = messageOrProperties;
} else if (typeof messageOrProperties === 'string') {
properties.message = messageOrProperties;
}
Object.assign(this, properties);
this.name = upperCamelCase(httpStatusCodes[statusCode]) || statusCode + ' Error';
this.statusCode = statusCode;
this.status = statusCode;
this.message = this.message || httpStatusCodes[statusCode];
Object.defineProperties(this, {
statusCode: { enumerable: false },
status: { enumerable: false },
name: { enumerable: false }
});
}
util.inherits(HttpError, Error);
Object.keys(httpStatusCodes).forEach(function(statusCode) {
statusCode = Number(statusCode);
if (statusCode >= 400) {
var SpecificHttpError = function(messageOrProperties, properties) {
HttpError.call(this, statusCode, messageOrProperties, properties);
};
var upperCamelCasedStatusMessage = upperCamelCase(httpStatusCodes[statusCode]);
HttpError[upperCamelCasedStatusMessage] = SpecificHttpError;
HttpError[statusCode] = SpecificHttpError;
util.inherits(SpecificHttpError, HttpError);
}
});
function upperCamelCase(string) {
return capitalize(camelCase(string));
}
module.exports = HttpError;