@shopgate/pwa-core 7.32.2-alpha.6 → 7.32.2-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/helpers/error.js +56 -0
- package/package.json +1 -1
package/helpers/error.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Describes a value without its content, since it can be personal data.
|
|
3
|
+
* @param {*} value The value.
|
|
4
|
+
* @returns {string} Primitives and errors as text, objects as their keys and their error code.
|
|
5
|
+
*/
|
|
6
|
+
export const describeValue = value => {
|
|
7
|
+
if (Array.isArray(value)) {
|
|
8
|
+
return `[${value.map(describeValue).join(', ')}]`;
|
|
9
|
+
}
|
|
10
|
+
if (!value || typeof value !== 'object' || value instanceof Error) {
|
|
11
|
+
return String(value);
|
|
12
|
+
}
|
|
13
|
+
const code = typeof value.code === 'string' ? `code: "${value.code}", ` : '';
|
|
14
|
+
return `{${code}keys: ${Object.keys(value).join(', ')}}`;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Defines properties on an error itself, so that they also replace properties the error only
|
|
19
|
+
* has a getter for.
|
|
20
|
+
* @param {Error} error The error.
|
|
21
|
+
* @param {Object} properties The properties to add.
|
|
22
|
+
* @returns {Error} The error.
|
|
23
|
+
*/
|
|
24
|
+
const defineProperties = (error, properties) => {
|
|
25
|
+
Object.keys(properties).forEach(key => {
|
|
26
|
+
Object.defineProperty(error, key, {
|
|
27
|
+
value: properties[key],
|
|
28
|
+
writable: true,
|
|
29
|
+
enumerable: true,
|
|
30
|
+
configurable: true
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
return error;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Turns a thrown value into an error and adds properties to it. It never throws.
|
|
38
|
+
* @param {*} thrown The thrown value.
|
|
39
|
+
* @param {Object} [properties={}] The properties to add.
|
|
40
|
+
* @returns {Error} The value itself when it is an error that takes the properties, otherwise an
|
|
41
|
+
* error that describes it.
|
|
42
|
+
*/
|
|
43
|
+
export const toError = (thrown, properties = {}) => {
|
|
44
|
+
/**
|
|
45
|
+
* @returns {Error} A new error that describes the thrown value.
|
|
46
|
+
*/
|
|
47
|
+
const describeThrown = () => defineProperties(new Error(describeValue(thrown)), properties);
|
|
48
|
+
if (!(thrown instanceof Error)) {
|
|
49
|
+
return describeThrown();
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
return defineProperties(thrown, properties);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return describeThrown();
|
|
55
|
+
}
|
|
56
|
+
};
|