forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exception.base.ts
67 lines (62 loc) · 1.85 KB
/
exception.base.ts
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
import { RequestContextService } from '@libs/application/context/AppRequestContext';
export interface SerializedException {
message: string;
code: string;
correlationId: string;
stack?: string;
cause?: string;
metadata?: unknown;
/**
* ^ Consider adding optional `metadata` object to
* exceptions (if language doesn't support anything
* similar by default) and pass some useful technical
* information about the exception when throwing.
* This will make debugging easier.
*/
}
/**
* Base class for custom exceptions.
*
* @abstract
* @class ExceptionBase
* @extends {Error}
*/
export abstract class ExceptionBase extends Error {
abstract code: string;
public readonly correlationId: string;
/**
* @param {string} message
* @param {ObjectLiteral} [metadata={}]
* **BE CAREFUL** not to include sensitive info in 'metadata'
* to prevent leaks since all exception's data will end up
* in application's log files. Only include non-sensitive
* info that may help with debugging.
*/
constructor(
readonly message: string,
readonly cause?: Error,
readonly metadata?: unknown,
) {
super(message);
Error.captureStackTrace(this, this.constructor);
const ctx = RequestContextService.getContext();
this.correlationId = ctx.requestId;
}
/**
* By default in NodeJS Error objects are not
* serialized properly when sending plain objects
* to external processes. This method is a workaround.
* Keep in mind not to return a stack trace to user when in production.
* https://iaincollins.medium.com/error-handling-in-javascript-a6172ccdf9af
*/
toJSON(): SerializedException {
return {
message: this.message,
code: this.code,
stack: this.stack,
correlationId: this.correlationId,
cause: JSON.stringify(this.cause),
metadata: this.metadata,
};
}
}