-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApplicationError.js
More file actions
473 lines (424 loc) · 13 KB
/
ApplicationError.js
File metadata and controls
473 lines (424 loc) · 13 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import ErrorTypes from './ErrorTypes.js'
import assert from 'assert'
/**
* @requires {@link module:lib/errors.ErrorTypes}
* @description
* Prototipo de erro da aplicacao
* Classe que extende de Error (nativo) e representa um erro no sistema.
* Esta classe promove iterface para organização de erros e tratamento para o client,
* convertendo para JSON os erros sendo possivel captura-los no clientside
* @extends Error
* @class ApplicationError
* @author Rafael Freitas
* @date Feb 13 2018
* @memberof module:lib/errors
* @updatedon Mar 19 2025
* @example
* // constructor 1
* new ApplicationError('COD001: Ocorreu um erro', customErrObj)
*
* // constructor 2
* new ApplicationError({
* code: 'COD001',
* message: 'Ocorreu um erro',
* details: customErrObj
* })
*/
/**
* Metodo para converter o Erro em objeto literal
*/
Error.prototype.toObject = function () {
return ApplicationError.toObject(this)
}
export default class ApplicationError extends Error {
/**
* ApplicationError.assert()
*
* Wrapper para a lib assert do Node.
* Cria um objeto dinamicamente copiando todos os metodos da lib assert instanciando a classe ApplicationError como erro da assertation
*
* Exemplo:
* ApplicationError.assert.ok()
* ApplicationError.assert.equal()
* ApplicationError.assert.fail()
*
*/
static get assert () {
const ErrorClass = this
// encapsular o metodo assert() para usar a instancia da classe ApplicationError invés de classe nativa AssertionError
const assertation = (test, message) => {
let err = {
message,
family: this.family || 'assert'
}
if (typeof message === 'object') {
err = {
...message,
family: message.family || 'assert'
}
}
assert(test, new ErrorClass(err))
}
// criar warppers dinamicos para cada metodo da lib assert passando convertendo a string de messagem em uma instancia da classe de erro
for (const key in assert) {
if (Object.prototype.hasOwnProperty.call(assert, key)) {
const fn = assert[key]
// obter a mensagem padrao
const { message } = new assert.AssertionError({
operator: key
})
Object.assign(assertation, {
[key]: (...args) => {
// remover o ultimo parametro que na maioria dos metodos sao o message
// assert.ok(value[, message])
const myMessage = args.pop()
// se o ultimo parametro nao for uma string usar a mensagem padrao do metodo de assertation
if (typeof myMessage === 'string') {
fn.apply(assert, args, new ErrorClass({message: myMessage, family: 'assert'}))
} else {
// usar mensagem padrao
fn.apply(assert, args, new ErrorClass({message, family: 'assert'}))
}
}
})
// ----> casos especiais -------------------
// assert.fail(actual, expected[, message[, operator[, stackStartFn]]])
Object.assign(assertation, {
fail: (actual, expected, myMessage, operator, stackStartFn) => {
if (typeof myMessage === 'string') {
fn.apply(assert, actual, expected, new ErrorClass({message: myMessage, family: 'assert'}), operator, stackStartFn)
} else {
// usar mensagem padrao
fn.apply(assert, actual, expected, new ErrorClass({message, family: 'assert'}), operator, stackStartFn)
}
}
})
}
}
// ----> inteface customizada -------------------
Object.assign(assertation, {
/**
* Testa se um valor tem é de um tipo primitivo especifico
* Ex: assert.type('uma string', String) -> se o valor passado nao for uma string um erro será lançado
*/
type: (value, Type, myMessage) => {
let type = String(Type)
if (typeof Type === 'function') {
type = Type.name.toLowerCase()
}
if (type === 'array') {
if (!Array.isArray(value)) {
assert.fail(new ErrorClass({message: myMessage || 'Asseration Failed', family: 'assert'}))
}
return
}
if (typeof value !== type) {
assert.fail(new ErrorClass({message: myMessage || 'Asseration Failed', family: 'assert'}))
}
},
array: (value, myMessage) => {
assertation.type(value, Array, myMessage)
},
string: (value, myMessage) => {
assertation.type(value, String, myMessage)
},
number: (value, myMessage) => {
assertation.type(value, Number, myMessage)
},
boolean: (value, myMessage) => {
assertation.type(value, Boolean, myMessage)
},
function: (value, myMessage) => {
assertation.type(value, Function, myMessage)
},
object: (value, myMessage) => {
if (value === null) {
assert.fail(new ErrorClass({message: myMessage || 'Asseration Failed', family: 'assert'}))
}
assertation.type(value, Object, myMessage)
},
notEmpty: (value, myMessage) => {
if (value === null) {
assert.fail(new ErrorClass({message: myMessage || 'Null value', family: 'assert'}))
}
switch (typeof value) {
case 'string':
assert.notEqual(value, '', new ErrorClass({message: myMessage || 'Empty string', family: 'assert'}))
break
case 'array':
assert.notEqual(value.length, 0, new ErrorClass({message: myMessage || 'Array is empty', family: 'assert'}))
break
case 'boolean':
this.boolean(value, myMessage)
break
case 'number':
this.number(value, myMessage)
break
case 'function':
this.function(value, myMessage)
break
default:
assert(value, new ErrorClass({message: myMessage || 'Assertation error for not empty value', family: 'assert'}))
}
}
})
return assertation
}
constructor () {
const [properties, details] = arguments
let [message, code] = arguments
if (typeof message === 'string') {
super(message)
} else if (properties.message) {
const { message } = properties
super(message)
} else {
super('unknown error')
}
// pode ser passado pela classe que herdar
if (typeof this.type === 'undefined') {
this.type = ErrorTypes.RUNTIME
}
if (typeof this.family !== 'string') {
this.family = ''
}
if (typeof details === 'object') {
this.details = details
}
// details foi passado como segundo parametro
if (typeof code !== 'string') {
code = null
}
// Saving class name in the property of our custom error as a shortcut.
// this.name = this.constructor.name
// Capturing stack trace, excluding constructor call from it.
Error.captureStackTrace(this, this.constructor)
// se o primeiro parametro for um objeto importar para a instancia
// {code: 1, message: 'Ocorreu um erro' ...}
if (typeof properties === 'object') {
const { name, stack, message, family } = properties
// copiar todos as propriedades do Error ou JSON para a instancia
Object.assign(this, properties)
if (name) {
this.name = name
this.errorClass = name
}
if (message) {
this.message = message
}
if (family) {
this.family = family
}
if (stack) {
this.stack = String(stack)
}
}
// convert "COD001: Meu erro" para {code: 'FAMILY#MOD.COD001', message: 'Meu erro', family: 'FAMILY'}
const strip = this.stripCodeFromDescription(this.message, this.code || code)
if (strip.code) {
this.code = strip.code
}
if (strip.message) {
this.message = strip.message
}
if (strip.family) {
this.family = strip.family
}
if (strip.uri) {
this.uri = strip.uri
}
if (!this.code) {
this.code = 'UKW'
}
if (!this.message) {
this.message = 'application unknown error'
}
if (!this.time) {
this.time = new Date()
}
// configurar o erro.isThrowable atributo dinamico
const self = this
Object.defineProperty(this, 'isThrowable', {
get: function () { return self.type < ErrorTypes.THROWABLE },
// writable: false,
configurable: false
})
}
/**
* setCode - Atribui um codigo com a familia do erro
* family: 'ERR'
* code: 001
* @memberof module:lib/errors.ApplicationError
* @instance
* @param {string} code Description
* @instance
* @example
* setCode(001) -> 'ERR001'
*/
setCode (code) {
this._code = code
this.code = this.family + code
}
setType (type) {
this.type = type
}
/**
* setFamily - Profixo do erro
* @memberof module:lib/errors.ApplicationError
* @instance
* @instance
* @param {string} family
*/
setFamily (family) {
this.family = family
this.setCode(this._code || this.code)
}
/**
* toJSON - retorna um objeto representando a instancia do erro durante
* serializacao para JSON
* @memberof module:lib/errors.ApplicationError
* @instance
* @instance
* @returns {object}
*/
toJSON () {
const error = Object.assign({},
ApplicationError.toObject(this), this, {
details: ApplicationError.toObject(this.details)
})
return JSON.stringify(error)
}
/**
* toString - formata o erro para string
* @memberof module:lib/errors.ApplicationError
* @instance
* @returns {string}
*/
toString () {
const p = []
p.push(`${this.errorClass || this.constructor.name}:`)
if (this.code) {
p.push(`[${this.code}]`)
}
p.push(this.message)
return p.join(' ')
}
/**
* throw - Levantar erro automaticamente
* @memberof module:lib/errors.ApplicationError
* @instance
* Promise.catch(err.throw)
* @instance
*/
throw () {
if (this.isThrowable) {
const self = this
throw self
}
}
/**
* stripCodeFromDescription - Convert "COD001: Meu erro" para {code: 'COD001', message: 'Meu erro'}
* @memberof module:lib/errors.ApplicationError
* @instance
* @param {string} description Description
* @param {string} [code=] Description
* @returns {object}
*/
stripCodeFromDescription (description, code = '') {
let strip = { code: code || '', message: String(description) }
const regex = /^(?:([\w\._-]+)\/)?(?:([\w\._-]+)#)?([\w\.]+):(.*)$/
const match = description.match(regex)
if (match) {
const [_, uri, family, code, message] = match
return { uri, family, code, message: String(message).trim() }
}
return strip
}
/**
* toObject - convert um Error nativo para objeto
* Se passar um objeto diferente de uma instancia de Error retorna ele mesmo
* @memberof module:lib/errors.ApplicationError
* @param {Error} err
* @static
* @returns {object}
*/
static toObject (err) {
if (err instanceof Error) {
const json = Object.assign({}, err, {
name: err.errorClass || err.constructor.name,
message: err.message,
stack: String(err.stack)
})
for (const key in json) {
if (Object.prototype.isPrototypeOf.call(json, key)) {
const value = json[key]
json[key] = this.toObject(value)
}
}
// if (err.details) {
// err.details = this.toObject(err.details)
// }
return json
}
return err
}
/**
* @memberof module:lib/errors.ApplicationError
* @param {Object} error
* @return {Promise<Object>}
*/
static wrapper (error) {
if (error.type === ErrorTypes.PROC_CANCELED) {
return Promise.resolve(null)
}
if (error instanceof ApplicationError) {
throw error
}
const errorWraped = new ApplicationError(error)
errorWraped.setFamily('unknown')
errorWraped.details = error
throw errorWraped
}
/**
* @memberof module:lib/errors.ApplicationError
* @return {Error<ApplicationError>}
*/
static cancelProc () {
const error = new ApplicationError('')
error.type = ErrorTypes.PROC_CANCELED
throw error
}
/**
* Converter um Error do Autobahn para ApplicationError
* @memberof module:lib/errors.ApplicationError
* @return {Error<ApplicationError>}
* @param err Object
*/
static parse (error) {
if (error instanceof ApplicationError) {
return error
}
// tipo de erro do Autobahn
if (error.error && Array.isArray(error.args)) {
const [err] = error.args
let parsedJsonError
try {
// quando o erro está encadeado
parsedJsonError = JSON.parse(err)
return new ApplicationError(parsedJsonError)
} catch (ex) {
}
if (typeof err === 'string') {
return new this({
type: ErrorTypes.CONNECTION,
code: error.error,
family: 'wamp',
message: err,
details: error
})
}
return new this(err, error)
}
return new this(error)
}
}