-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (49 loc) · 1.23 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
'use strict';
const ExtendableError = require('es6-error');
class ServiceError extends ExtendableError {
constructor(code, msg, extra = {}, logger) {
// if second param is Error object, retrieve it's message
if (msg instanceof Error) {
msg = msg.message;
}
if (code instanceof ServiceError || isObject(code)) {
const instance = code;
if (typeof msg !== 'string') {
extra = msg;
}
msg = instance.message;
extra = { ...instance, ...extra };
code = instance.code;
}
super(msg);
this.code = code;
Object.assign(this, extra);
if (logger && logger.error) {
logger.error({
...extra,
code: this.code,
message: msg,
});
}
}
}
function isObject(obj) {
return obj === Object(obj);
}
function ServiceErrorFactory(logger) {
return function fn(...args) {
while (args.length < 3) {
args.push({});
}
const err = new ServiceError(...args, logger);
// fn is the wrapper function which is the frame above new ServiceError, omit it
if (Error.hasOwnProperty('captureStackTrace')) {
Error.captureStackTrace(err, fn);
}
return err;
};
}
module.exports = {
ServiceError,
ServiceErrorFactory,
};