@alexsasharegan/

Wrapping Errors #1

Nodejs

https://blog.parametricstudios.com/posts/wrapping-errors/

fork
loading
Files
  • index.js
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
class WrappedError extends Error {
	constructor(message /* context */, previous /* original error value */) {
		// First we have to call the Error constructor with its expected arguments.
		super(message);
		// We update the error's name to distinguish it from the base Error.
		this.name = this.constructor.name;
		// We add our reference to the original error value (if provided).
		this.previous = previous;
	}

	get root() {
		// Base case, no child === this instance is root
		if (this.previous == null) {
			return this;
		}
		// When the child is another node, compute recursively
		if (this.previous instanceof WrappedError) {
			return this.previous.root;
		}
		// This instance wraps the original error
		return this.previous;
	}

	get spans() {
		let spans = [];
		let err = this;

		while (err instanceof WrappedError) {
			spans.push(err.toString());
			err = err.previous;
		}

		if (err == null) {
			return spans;
		}

		if (err instanceof Error) {
			spans.push(err.toString());
		} else {
			spans.push(String(err));
		}

		return spans;
	}
}

let error1 = new Error("the first error");
let error2 = new WrappedError("the second error wraps #1", error1);
let error3 = new WrappedError("the third error wraps #2", error2);

console.assert(
	error2.root === error1,
	"the root of error2 should be strictly equal to error1"
);
console.assert(
	error3.root === error1,
	"the root of error3 should be strictly equal to error1"
);
// Passes if no error appears in the console

console.error(error3.spans);