@smbcheeky/error-object-from-payload 1.2.0 → 1.2.1

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/README.md CHANGED
@@ -4,176 +4,286 @@
4
4
  [![GitHub last commit](https://img.shields.io/github/last-commit/smbcheeky/error-object-from-payload)](https://github.com/smbcheeky/error-object-from-payload)
5
5
  [![GitHub stars](https://img.shields.io/github/stars/smbcheeky/error-object-from-payload)](https://img.shields.io/github/stars/smbcheeky/error-object-from-payload)
6
6
 
7
+ # ErrorObjectFromPayload
8
+
9
+ Create [`ErrorObject`](https://github.com/SMBCheeky/error-object) instances from any payload — API responses, caught
10
+ exceptions, or unknown objects — using simple path-based rules. Get step-by-step debugging logs for the entire process.
11
+
7
12
  ## TL;DR
8
13
 
9
- - Install the package `npm install @smbcheeky/error-object @smbcheeky/error-object-from-payload`
10
- - Write `new ErrorObjectFromPayload(<pick an api response with an error>).verboseLog('LOG')` and use the info provided to
11
- map your error
12
- - :tada:
13
- - oh... and check the [playground](https://github.com/SMBCheeky/error-object-from-payload/blob/main/playground/index.ts)
14
- file
14
+ ```bash
15
+ npm install @smbcheeky/error-object @smbcheeky/error-object-from-payload
16
+ ```
17
+
18
+ ```typescript
19
+ new ErrorObjectFromPayload(<any error-like payload>).debugLog('LOG');
20
+ // Use the debug output to understand what was found and adjust your options
21
+ ```
22
+
23
+ Then check the [playground](https://github.com/SMBCheeky/error-object-from-payload/blob/main/playground/index.ts) for
24
+ detailed, step-by-step examples.
15
25
 
16
26
  ## Installation
17
27
 
18
- `npm install @smbcheeky/error-object @smbcheeky/error-object-from-payload`
19
-
20
- `yarn add @smbcheeky/error-object @smbcheeky/error-object-from-payload`
21
-
22
- ## Description
23
-
24
- The ErrorObject class is made to extend `Error` enabling type guard checks like `errorObject instanceof Error`,
25
- `errorObject instanceof ErrorObject`, ErrorObject.is() and isErrorObject(). . The `ErrorObject` class is backwards
26
- compatible with `Error`.
27
-
28
- This functionality was extracted from the [error-object](https://github.com/SMBCheeky/error-object) package (at v1.1.5)
29
- and renamed to `error-object-from-payload` to simplify the main package and its README. This package is not a
30
- replacement for the `error-object` package, it is just a helper to simplify the process of creating errors from any
31
- payload by providing step-by-step debugging logs for the entire process.
32
-
33
- ## Usage
34
-
35
- Use `new ErrorObjectFromPayload(<anything>, ErrorObjectBuildOptions)` to create errors from any input.
36
-
37
- The processing of the ErrorObject is done in a few steps, based on the `ErrorObjectBuildOptions`:
38
-
39
- - first the initial object is checked via the options `checkInputObjectForValues` and `checkInputObjectForTypes` and
40
- `checkInputObjectForKeys`
41
- - then the objects checks for an object array at `pathToErrors`, which could be an array of errors
42
- - if an error array is found, the process will consider all other paths relative to the objects in the error array found
43
- - if an error array is not found, the process will consider all other paths absolute to the initial object passed to
44
- `new ErrorObjectFromPayload()`
45
- - the `pathToCode`, `pathToNumberCode`, `pathToMessage`, `pathToDetails` and `pathToDomain` options are used to map
46
- values to their associated field, if found
47
- - for all fields other than `numberCode`, if a value is found and is a string, it is saved as is, but if it is an array
48
- or an object, it will be JSON.stringify and saved as a string
49
- - for `numberCode`, if a value is found, and it is a number different from `NaN`, it is saved
50
- - the `transform` function is used to transform the found values by the parsing process into the error object
51
- - the transform function has access to all pre-transformation values and also the initial object (object inside the
52
- errors' array or initial object)
53
- - everything gets processed into a list of `ErrorSummary | ErrorObjectErrorResult` array
54
- - it contains everything, from error strings custom-made to be as distinct and easy to read as possible, to
55
- self-documenting summaries of what values are found, at which path, if an error object was found, etc.
56
- - the count of the list is meant to be an indication of how many input objects were found and processed, as each of them
57
- should become an error object
58
- - in the last step of the process, the list is filtered down and a single error object is created, with everything baked
59
- in
60
- - the `raw` will contain details about the process and also the initial/input object
61
- - check `processingErrors` and `summary` fields in `raw` object for the errors and the summaries that were
62
- computed during the process
63
- - the `nextErrors` array allows for all errors found to be saved on one single error object for later use
64
-
65
- ## Usage & Examples
66
-
67
- For a guide on how to use the library, please check the first detailed example in
68
- the [playground](https://github.com/SMBCheeky/error-object/blob/main/playground/index.ts) file.
28
+ ```bash
29
+ npm install @smbcheeky/error-object @smbcheeky/error-object-from-payload
30
+ ```
31
+
32
+ ```bash
33
+ yarn add @smbcheeky/error-object @smbcheeky/error-object-from-payload
34
+ ```
35
+
36
+ Both packages are required — `ErrorObjectFromPayload` extends `ErrorObject`.
37
+
38
+ ## Why This Package?
39
+
40
+ [`ErrorObject`](https://github.com/SMBCheeky/error-object) gives you structured, chainable errors. But when you're
41
+ dealing with API responses, third-party payloads, or caught exceptions, you need a way to _extract_ an error from
42
+ messy, inconsistent data.
43
+
44
+ `ErrorObjectFromPayload` does that — you give it any object and a set of path-based rules, and it figures out the code,
45
+ message, details, and domain. When something doesn't map correctly, the debug output tells you exactly what was found,
46
+ where, and what went wrong.
47
+
48
+ ## Quick Start
49
+
50
+ ```typescript
51
+ import { ErrorObjectFromPayload } from '@smbcheeky/error-object-from-payload';
52
+
53
+ // Pass any error-like object it just works with common patterns
54
+ new ErrorObjectFromPayload({
55
+ error: { code: 'auth/invalid-email', message: 'The email address is badly formatted.' },
56
+ }).debugLog('LOG');
57
+
58
+ // [LOG] The email address is badly formatted. [auth/invalid-email]
59
+ // [DEBUG] { "code": "auth/invalid-email", "message": "The email address is badly formatted.", "raw": { ... } }
60
+ ```
61
+
62
+ ## How It Works
63
+
64
+ `ErrorObjectFromPayload` processes your input based on `ErrorObjectBuildOptions`:
65
+
66
+ 1. **Input validation** checks the input object using `checkInputObjectForValues`, `checkInputObjectForTypes`, and
67
+ `checkInputObjectForKeys`. If a check fails, processing stops early.
68
+
69
+ 2. **Error array detection** — looks for an array at `pathToErrors` (e.g. `['errors']`). If found, each element is
70
+ processed separately and all other paths become relative to those elements.
71
+
72
+ 3. **Value extraction** — resolves `pathToCode`, `pathToNumberCode`, `pathToMessage`, `pathToDetails`, and
73
+ `pathToDomain` against each error object. String values are kept as-is; arrays and objects are `JSON.stringify`'d.
74
+
75
+ 4. **Transform** the optional `transform` function receives all extracted values and the source object, letting you
76
+ remap codes to messages, derive domains, or apply any custom logic.
77
+
78
+ 5. **Result** — the first valid error (with both `code` and `message`) becomes the `ErrorObjectFromPayload`. Additional
79
+ errors are stored in `nextErrors`. The `raw` property contains `processingErrors`, `summary`, and the original input
80
+ for debugging.
81
+
82
+ ## Build Options
83
+
84
+ ```typescript
85
+ new ErrorObjectFromPayload(payload, {
86
+ // Pre-checks — skip processing if the input doesn't match
87
+ checkInputObjectForValues: { status: { value: 'error', exists: true } },
88
+ checkInputObjectForTypes: { data: { type: 'object', exists: true } },
89
+ checkInputObjectForKeys: { error: { exists: true } },
90
+
91
+ // Path to an array of errors (paths become relative to each element)
92
+ pathToErrors: ['errors', 'errs'],
93
+
94
+ // Paths to error properties (first match wins)
95
+ pathToCode: ['code', 'error.code'],
96
+ pathToNumberCode: ['numberCode'],
97
+ pathToMessage: ['message', 'error.message'],
98
+ pathToDetails: ['details', 'error.details'],
99
+ pathToDomain: ['domain', 'type'],
100
+
101
+ // Transform extracted values before creating the error
102
+ transform: (beforeTransform, inputObject) => ({
103
+ ...beforeTransform,
104
+ message: beforeTransform.code === 'timeout' ? 'Request timed out.' : beforeTransform.message,
105
+ }),
106
+ });
107
+ ```
108
+
109
+ All paths support dot notation for nesting (e.g. `error.context.reason`) and numeric indices for arrays
110
+ (e.g. `errors.0.code`).
111
+
112
+ ## Default Options
113
+
114
+ The library ships with sensible defaults that cover common API error patterns:
69
115
 
70
116
  ```typescript
71
- new ErrorObject({ code: '', message: 'Something went wrong.', domain: 'auth' }).debugLog('LOG');
72
-
73
- new ErrorObjectFromPayload({ code: '', message: 'Something went wrong', domain: 'auth' })?.force?.debugLog('LOG');
74
-
75
- // Example 12 output:
76
- //
77
- // [LOG] Something went wrong. [auth]
78
- // {
79
- // "code": "",
80
- // "message": "Something went wrong.",
81
- // "domain": "auth"
82
- // }
83
- //
84
- // [LOG] Something went wrong [auth]
85
- // {
86
- // "code": "",
87
- // "message": "Something went wrong",
88
- // "domain": "auth"
89
- // }
117
+ {
118
+ pathToErrors: ['errors', 'errs'],
119
+ pathToCode: addPrefixPathVariants('error', ['code', 'err_code', 'errorCode', 'error_code']),
120
+ pathToNumberCode: addPrefixPathVariants('error', ['numberCode', 'err_number_code', ...]),
121
+ pathToMessage: addPrefixPathVariants('error', ['message', 'err_message', 'errorMessage', ...]),
122
+ pathToDetails: addPrefixPathVariants('error', ['details', 'err_details', 'errorDetails', ...]),
123
+ pathToDomain: addPrefixPathVariants('error', ['domain', 'errorDomain', 'type', ...]),
124
+ transform: /* auto-converts numberCode to code string if code is missing */,
125
+ }
90
126
  ```
91
127
 
128
+ Use `addPrefixPathVariants('error', ['code'])` to generate `['code', 'error.code']` — handy when the error might be
129
+ nested or at the root.
130
+
131
+ ## Logging
132
+
133
+ `ErrorObjectFromPayload` inherits all logging from `ErrorObject` and adds `verboseLog()`:
134
+
92
135
  ```typescript
93
- const response = {
94
- statusCode: 400,
95
- headers: {
96
- 'Content-Type': 'application/json',
136
+ error.log('TAG'); // toString() message + code
137
+ error.debugLog('TAG'); // toDebugString() — includes full JSON with raw
138
+ error.verboseLog('TAG'); // toVerboseString() — debugLog + nextErrors (if any)
139
+ ```
140
+
141
+ All methods return `this` for inline chaining.
142
+
143
+ ## Multiple Errors
144
+
145
+ When `pathToErrors` finds an array with multiple entries, the first becomes the main error and the rest are stored in
146
+ `nextErrors`:
147
+
148
+ ```typescript
149
+ const error = new ErrorObjectFromPayload(
150
+ {
151
+ error: {
152
+ errors: [
153
+ { code: 'auth/invalid-email', message: 'The email address is badly formatted.' },
154
+ { code: 'auth/weak-password', message: 'The password is too weak.' },
155
+ ],
156
+ },
97
157
  },
98
- body: '{"error":"Invalid input data","code":400}',
99
- };
158
+ { pathToErrors: ['error.errors'] },
159
+ );
160
+
161
+ error.debugLog('AUTH');
162
+ // [AUTH][1] The email address is badly formatted. [auth/invalid-email]
163
+ // [DEBUG] { ... }
164
+ // [AUTH][2] The password is too weak. [auth/weak-password]
165
+ // [DEBUG] { ... }
166
+
167
+ error.nextErrors; // [ErrorObjectFromPayload { code: 'auth/weak-password', ... }]
168
+ ```
169
+
170
+ ## Debugging
171
+
172
+ When an error can't be built (missing code or message), `ErrorObjectFromPayload` returns a fallback error. Use
173
+ `.isFallback()` to check and `.debugLog()` to see what went wrong:
174
+
175
+ ```typescript
176
+ const error = new ErrorObjectFromPayload(somePayload);
177
+
178
+ if (error.isFallback()) {
179
+ error.debugLog('FALLBACK');
180
+ // Check raw.processingErrors for what failed
181
+ // Check raw.summary for what values were found at which paths
182
+ }
183
+ ```
184
+
185
+ ## Static Configuration
186
+
187
+ ```typescript
188
+ // Show detailed console.log output during error building (default: true)
189
+ ErrorObjectFromPayload.SHOW_ERROR_LOGS = false;
190
+
191
+ // Show domain in toString() output (default: false, from ErrorObject 1.2.1)
192
+ ErrorObject.INCLUDE_DOMAIN_IN_STRING = true;
193
+
194
+ // Customize the log method
195
+ ErrorObject.LOG_METHOD = myLogger.error;
100
196
 
101
- new ErrorObjectFromPayload(JSON.parse(response?.body), {
197
+ // Disable logging entirely
198
+ ErrorObject.LOG_METHOD = null;
199
+ ```
200
+
201
+ ## Examples
202
+
203
+ ### Parse a REST API error
204
+
205
+ ```typescript
206
+ new ErrorObjectFromPayload(JSON.parse(response.body), {
102
207
  pathToNumberCode: ['code'],
103
208
  pathToMessage: ['error'],
104
- }).force?.debugLog('LOG');
105
-
106
- // Example 6 output:
107
- //
108
- // [LOG] Invalid input data [400]
109
- // {
110
- // "code": "400",
111
- // "numberCode": 400,
112
- // "message": "Invalid input data"
113
- // }
209
+ }).debugLog('API');
210
+
211
+ // [API] Invalid input data [400]
212
+ // [DEBUG] { "code": "400", "numberCode": 400, "message": "Invalid input data", "raw": { ... } }
114
213
  ```
115
214
 
215
+ ### Map error codes to user-facing messages
216
+
116
217
  ```typescript
117
- /*
118
- * You could have a file called `errors.ts` in each of your modules/folders and
119
- * define a function like `createAuthError2()` that returns an error object with
120
- * the correct message and domain.
121
- */
122
- const AuthMessageResolver = (beforeTransform: ErrorObjectTransformState): ErrorObjectTransformState => {
123
- // Quick tip: Make all messages slightly different, to make it easy
124
- // to find the right one when debugging, even in production
125
- let message: string | undefined;
126
- switch (beforeTransform.code) {
127
- case 'generic':
128
- message = 'Something went wrong';
129
- break;
130
- case 'generic-again':
131
- message = 'Something went wrong. Please try again.';
132
- break;
133
- case 'generic-network':
134
- message = 'Something went wrong. Please check your internet connection and try again.';
135
- break;
136
- default:
137
- message = 'Something went wrong.';
138
- }
139
- return { ...beforeTransform, message };
140
- };
141
-
142
- const createAuthError2 = (code: string) => {
143
- return new ErrorObjectFromPayload({ code, domain: 'auth' }, { transform: AuthMessageResolver });
144
- };
145
-
146
- createAuthError2('generic')?.error?.log('1');
147
- createAuthError2('generic-again')?.error?.log('2');
148
- createAuthError2('generic-network')?.error?.log('3');
149
- createAuthError2('invalid-code')?.error?.log('4');
150
-
151
- // Example 2 output:
152
- //
153
- // [1] Something went wrong [auth/generic]
154
- // [2] Something went wrong. Please try again. [auth/generic-again]
155
- // [3] Something went wrong. Please check your internet connection and try again. [auth/generic-network]
156
- // [4] Something went wrong. [auth/invalid-code]
218
+ const createAuthError = (code: string) =>
219
+ new ErrorObjectFromPayload(
220
+ { code, domain: 'auth' },
221
+ {
222
+ transform: (state) => {
223
+ const messages: Record<string, string> = {
224
+ 'generic': 'Something went wrong',
225
+ 'generic-again': 'Something went wrong. Please try again.',
226
+ 'generic-network': 'Please check your internet connection.',
227
+ };
228
+ return { ...state, message: messages[state.code ?? ''] ?? 'Something went wrong.' };
229
+ },
230
+ },
231
+ );
232
+
233
+ createAuthError('generic').log('1'); // [1] Something went wrong [auth/generic]
234
+ createAuthError('generic-again').log('2'); // [2] Something went wrong. Please try again. [auth/generic-again]
235
+ createAuthError('generic-network').log('3'); // [3] Please check your internet connection. [auth/generic-network]
236
+ ```
237
+
238
+ ### Parse a GraphQL error response
239
+
240
+ ```typescript
241
+ new ErrorObjectFromPayload(
242
+ {
243
+ errors: [
244
+ {
245
+ message: 'Cannot query field "username" on type "User"',
246
+ locations: [{ line: 2, column: 3 }],
247
+ extensions: { code: 'GRAPHQL_VALIDATION_FAILED' },
248
+ },
249
+ ],
250
+ data: null,
251
+ },
252
+ {
253
+ pathToCode: ['extensions.code'],
254
+ pathToMessage: ['message'],
255
+ pathToDetails: ['locations'],
256
+ checkInputObjectForValues: { data: { value: null, exists: true } },
257
+ },
258
+ ).debugLog('GQL');
259
+
260
+ // [GQL] Cannot query field "username" on type "User" [GRAPHQL_VALIDATION_FAILED]
261
+ // [DEBUG] { "code": "GRAPHQL_VALIDATION_FAILED", "message": "...", "details": "[{...}]", "raw": { ... } }
157
262
  ```
158
263
 
159
264
  ## FAQ
160
265
 
161
- ### How do I use paths? Are they absolute?
266
+ ### Are paths absolute or relative?
267
+
268
+ Paths start as absolute (from the input root). If `pathToErrors` finds an array, all other paths become relative to each
269
+ element in that array. You can either set `pathToErrors` to `[]` and map from the root, or keep it and use relative
270
+ paths — the second approach is recommended as it handles multiple errors automatically.
271
+
272
+ ### The error code is sometimes in `error.code` and sometimes at the root...
273
+
274
+ Use `addPrefixPathVariants('error', ['code'])` to generate `['code', 'error.code']` — the first match wins.
275
+
276
+ ### Can I extract a raw value and process it later?
162
277
 
163
- To support inputs containing arrays of errors as well as single errors, all paths are treated initially as absolute
164
- (from the input root), but if an array of errors is detected, it will consider each element found the new root input
165
- object. Devs have a choice: set the "pathToErrors" option as empty, and then map only the first
166
- error (not recommended), or adjust the paths to be relative to the objects inside the detected errors array.
278
+ Yes. Use dot notation for any nesting depth (e.g. `error.details.0`). Non-string values are `JSON.stringify`'d. Use the
279
+ `transform` function to parse or reshape them. An `ErrorObject` needs at least `code` and `message` as strings.
167
280
 
168
- ### How do I use paths? I sometimes get the error code in an `error` object, and sometimes in the root object...
281
+ ### What's the difference between `ErrorObject` and `ErrorObjectFromPayload`?
169
282
 
170
- You can use `pathToCode: addPrefixPathVariants('error', ['code']),` or `pathToCode: ['error.code']`
283
+ Use `new ErrorObject(...)` when you know the code and message upfront. Use `new ErrorObjectFromPayload(...)` when you
284
+ need to extract them from an unknown payload. Both are `instanceof Error` and `instanceof ErrorObject`.
171
285
 
172
- ### How do I use paths? Can I get the raw contents of a path and process it later?
286
+ ## More Examples
173
287
 
174
- Yes, you can. You can use paths like `error.details.0` to get a raw value, and then process it later using the
175
- `transform` option.
176
- If the value is not a string, it will be converted to a string using `JSON.stringify` to ensure everything works as
177
- intended.
178
- Remember, for an ErrorObject to be created, it needs at least a code and a message, and both are required to be string
179
- values.
288
+ See the [playground](https://github.com/SMBCheeky/error-object-from-payload/blob/main/playground/index.ts) for 12
289
+ runnable examples covering GraphQL errors, REST APIs, nested payloads, validation errors, and more.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { ErrorObject } from '@smbcheeky/error-object';
2
2
 
3
+ declare let SHOW_ERROR_LOGS: boolean;
4
+ declare const setShowErrorLogs: (value: boolean) => void;
3
5
  /**
4
6
  * For customizing the paths, please make sure to use the {@link addPrefixPathVariants} function to also add the `error.` prefixed paths to the pathTo... arrays used in the {@link ErrorObjectBuildOptions} type.
5
7
  */
@@ -123,13 +125,16 @@ type ErrorObjectProcessingError = {
123
125
 
124
126
  /**
125
127
  * The {@link ErrorObjectFromPayload} class is an alternative way to create an {@link ErrorObject} from anything
126
- * resembling an error, even request payloads. It also chains errors using the `.setNextErrors()` method.
128
+ * resembling an error, even request payloads. It also chains errors using the `nextErrors` property.
127
129
  */
128
130
  declare class ErrorObjectFromPayload extends ErrorObject {
131
+ static get SHOW_ERROR_LOGS(): boolean;
132
+ static set SHOW_ERROR_LOGS(value: boolean);
129
133
  static DEFAULT_FALLBACK_TAG: string;
130
134
  nextErrors?: ErrorObjectFromPayload[];
131
135
  constructor(props: any, withOptions?: Partial<ErrorObjectBuildOptions>);
132
136
  static generic: () => ErrorObjectFromPayload;
137
+ verboseLog(logTag: string): this;
133
138
  protected _log(logTag: string, logLevel: 'log' | 'debug' | 'verbose'): this;
134
139
  toVerboseString(): string;
135
140
  /**
@@ -140,4 +145,4 @@ declare class ErrorObjectFromPayload extends ErrorObject {
140
145
  private static processErrorObjectResult;
141
146
  }
142
147
 
143
- export { DEFAULT_BUILD_OPTIONS, type ErrorObjectBuildOptions, type ErrorObjectErrorResult, ErrorObjectFromPayload, type ErrorObjectProcessingError, type ErrorObjectTransformState, type ErrorSummary, addPrefixPathVariants };
148
+ export { DEFAULT_BUILD_OPTIONS, type ErrorObjectBuildOptions, type ErrorObjectErrorResult, ErrorObjectFromPayload, type ErrorObjectProcessingError, type ErrorObjectTransformState, type ErrorSummary, SHOW_ERROR_LOGS, addPrefixPathVariants, setShowErrorLogs };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { ErrorObject } from '@smbcheeky/error-object';
2
2
 
3
+ declare let SHOW_ERROR_LOGS: boolean;
4
+ declare const setShowErrorLogs: (value: boolean) => void;
3
5
  /**
4
6
  * For customizing the paths, please make sure to use the {@link addPrefixPathVariants} function to also add the `error.` prefixed paths to the pathTo... arrays used in the {@link ErrorObjectBuildOptions} type.
5
7
  */
@@ -123,13 +125,16 @@ type ErrorObjectProcessingError = {
123
125
 
124
126
  /**
125
127
  * The {@link ErrorObjectFromPayload} class is an alternative way to create an {@link ErrorObject} from anything
126
- * resembling an error, even request payloads. It also chains errors using the `.setNextErrors()` method.
128
+ * resembling an error, even request payloads. It also chains errors using the `nextErrors` property.
127
129
  */
128
130
  declare class ErrorObjectFromPayload extends ErrorObject {
131
+ static get SHOW_ERROR_LOGS(): boolean;
132
+ static set SHOW_ERROR_LOGS(value: boolean);
129
133
  static DEFAULT_FALLBACK_TAG: string;
130
134
  nextErrors?: ErrorObjectFromPayload[];
131
135
  constructor(props: any, withOptions?: Partial<ErrorObjectBuildOptions>);
132
136
  static generic: () => ErrorObjectFromPayload;
137
+ verboseLog(logTag: string): this;
133
138
  protected _log(logTag: string, logLevel: 'log' | 'debug' | 'verbose'): this;
134
139
  toVerboseString(): string;
135
140
  /**
@@ -140,4 +145,4 @@ declare class ErrorObjectFromPayload extends ErrorObject {
140
145
  private static processErrorObjectResult;
141
146
  }
142
147
 
143
- export { DEFAULT_BUILD_OPTIONS, type ErrorObjectBuildOptions, type ErrorObjectErrorResult, ErrorObjectFromPayload, type ErrorObjectProcessingError, type ErrorObjectTransformState, type ErrorSummary, addPrefixPathVariants };
148
+ export { DEFAULT_BUILD_OPTIONS, type ErrorObjectBuildOptions, type ErrorObjectErrorResult, ErrorObjectFromPayload, type ErrorObjectProcessingError, type ErrorObjectTransformState, type ErrorSummary, SHOW_ERROR_LOGS, addPrefixPathVariants, setShowErrorLogs };
package/dist/index.js CHANGED
@@ -39,15 +39,18 @@ var index_exports = {};
39
39
  __export(index_exports, {
40
40
  DEFAULT_BUILD_OPTIONS: () => DEFAULT_BUILD_OPTIONS,
41
41
  ErrorObjectFromPayload: () => ErrorObjectFromPayload,
42
- addPrefixPathVariants: () => addPrefixPathVariants
42
+ SHOW_ERROR_LOGS: () => SHOW_ERROR_LOGS,
43
+ addPrefixPathVariants: () => addPrefixPathVariants,
44
+ setShowErrorLogs: () => setShowErrorLogs
43
45
  });
44
46
  module.exports = __toCommonJS(index_exports);
45
- var import_error_object2 = require("@smbcheeky/error-object");
46
-
47
- // src/builder/index.ts
48
47
  var import_error_object = require("@smbcheeky/error-object");
49
48
 
50
49
  // src/utils.ts
50
+ var SHOW_ERROR_LOGS = true;
51
+ var setShowErrorLogs = (value) => {
52
+ SHOW_ERROR_LOGS = value;
53
+ };
51
54
  var addPrefixPathVariants = (prefix, array) => {
52
55
  if (typeof prefix === "string") {
53
56
  return array.concat(array.map((s) => typeof s === "string" ? `${prefix}.${s}` : s));
@@ -267,7 +270,7 @@ var buildSummariesFromObject = (input, withOptions) => {
267
270
  }
268
271
  return summaries;
269
272
  } catch (generalError) {
270
- import_error_object.ErrorObject.SHOW_ERROR_LOGS && console.log("[ErrorObject]", "Error during buildSummariesFromObject():", generalError);
273
+ SHOW_ERROR_LOGS && console.log("[ErrorObjectFromPayload]", "Error during buildSummariesFromObject():", generalError);
271
274
  return ["generalBuildSummariesFromObjectError"];
272
275
  }
273
276
  };
@@ -286,7 +289,7 @@ var buildSummaryFromObject = (maybeObject, errorsPath, didDetectErrorsArray, wit
286
289
  }
287
290
  } catch (e) {
288
291
  }
289
- if (objectToParse === maybeObject) {
292
+ if (objectToParse === void 0) {
290
293
  objectToParse = { code: "unknown", message: maybeObject };
291
294
  }
292
295
  }
@@ -377,7 +380,7 @@ var buildSummaryFromObject = (maybeObject, errorsPath, didDetectErrorsArray, wit
377
380
  }
378
381
  };
379
382
  } catch (generalError) {
380
- import_error_object.ErrorObject.SHOW_ERROR_LOGS && console.log("[ErrorObject]", "Error during buildSummaryFromObject():", generalError);
383
+ SHOW_ERROR_LOGS && console.log("[ErrorObjectFromPayload]", "Error during buildSummaryFromObject():", generalError);
381
384
  return "generalBuildSummaryFromObjectError";
382
385
  }
383
386
  };
@@ -398,7 +401,13 @@ var findNestedValueForPath = (value, path) => {
398
401
  };
399
402
 
400
403
  // src/index.ts
401
- var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error_object2.ErrorObject {
404
+ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error_object.ErrorObject {
405
+ static get SHOW_ERROR_LOGS() {
406
+ return SHOW_ERROR_LOGS;
407
+ }
408
+ static set SHOW_ERROR_LOGS(value) {
409
+ setShowErrorLogs(value);
410
+ }
402
411
  constructor(props, withOptions) {
403
412
  var _a, _b, _c, _d;
404
413
  if ("code" in props && props.code !== void 0 && props.code !== null && typeof props.code === "string" && "message" in props && props.message !== void 0 && props.message !== null && typeof props.message === "string") {
@@ -411,7 +420,7 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error
411
420
  } catch (error) {
412
421
  super({
413
422
  code: "INT-1",
414
- message: `Error during checkInputForInitialObject(). Details: ${(_b = (_a = error == null ? void 0 : error.toString) == null ? void 0 : _a.call(error)) != null ? _b : import_error_object2.ErrorObject.GENERIC_MESSAGE}}`,
423
+ message: `Error during checkInputForInitialObject(). Details: ${(_b = (_a = error == null ? void 0 : error.toString) == null ? void 0 : _a.call(error)) != null ? _b : import_error_object.ErrorObject.GENERIC_MESSAGE}`,
415
424
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
416
425
  raw: {
417
426
  error
@@ -421,8 +430,8 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error
421
430
  }
422
431
  if (checksFailed !== void 0) {
423
432
  super({
424
- code: import_error_object2.ErrorObject.GENERIC_CODE,
425
- message: import_error_object2.ErrorObject.GENERIC_MESSAGE,
433
+ code: import_error_object.ErrorObject.GENERIC_CODE,
434
+ message: import_error_object.ErrorObject.GENERIC_MESSAGE,
426
435
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
427
436
  raw: {
428
437
  processingErrors: [{ errorCode: checksFailed, summary: void 0 }]
@@ -453,8 +462,8 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error
453
462
  }
454
463
  }
455
464
  super({
456
- code: import_error_object2.ErrorObject.GENERIC_CODE,
457
- message: import_error_object2.ErrorObject.GENERIC_MESSAGE,
465
+ code: import_error_object.ErrorObject.GENERIC_CODE,
466
+ message: import_error_object.ErrorObject.GENERIC_MESSAGE,
458
467
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
459
468
  raw: {
460
469
  processingErrors: processingErrors.length > 0 ? processingErrors : void 0,
@@ -464,7 +473,7 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error
464
473
  } catch (error) {
465
474
  super({
466
475
  code: "INT-2",
467
- message: `Error during processErrorObjectResult(). Details: ${(_d = (_c = error == null ? void 0 : error.toString) == null ? void 0 : _c.call(error)) != null ? _d : import_error_object2.ErrorObject.GENERIC_MESSAGE}}`,
476
+ message: `Error during processErrorObjectResult(). Details: ${(_d = (_c = error == null ? void 0 : error.toString) == null ? void 0 : _c.call(error)) != null ? _d : import_error_object.ErrorObject.GENERIC_MESSAGE}`,
468
477
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
469
478
  raw: {
470
479
  error
@@ -473,33 +482,33 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends import_error
473
482
  }
474
483
  }
475
484
  }
485
+ verboseLog(logTag) {
486
+ return this._log(logTag, "verbose");
487
+ }
476
488
  _log(logTag, logLevel) {
489
+ if (!import_error_object.ErrorObject.LOG_METHOD) return this;
477
490
  const logForThis = logLevel === "verbose" ? this.toVerboseString() : logLevel === "debug" ? this.toDebugString() : this.toString();
478
491
  if (Array.isArray(this.nextErrors) && this.nextErrors.length > 0) {
479
492
  let row = 1;
480
- import_error_object2.ErrorObject.LOG_METHOD && typeof import_error_object2.ErrorObject.LOG_METHOD === "function" && import_error_object2.ErrorObject.LOG_METHOD(`[${logTag}][${row}]`, logForThis);
493
+ import_error_object.ErrorObject.LOG_METHOD(`[${logTag}][${row}]`, logForThis);
481
494
  for (const error of this.nextErrors) {
482
495
  row++;
483
- import_error_object2.ErrorObject.LOG_METHOD && typeof import_error_object2.ErrorObject.LOG_METHOD === "function" && import_error_object2.ErrorObject.LOG_METHOD(
496
+ import_error_object.ErrorObject.LOG_METHOD(
484
497
  `[${logTag}][${row}]`,
485
498
  logLevel === "verbose" ? error.toVerboseString() : logLevel === "debug" ? error.toDebugString() : error.toString()
486
499
  );
487
500
  }
488
501
  } else {
489
- import_error_object2.ErrorObject.LOG_METHOD && typeof import_error_object2.ErrorObject.LOG_METHOD === "function" && import_error_object2.ErrorObject.LOG_METHOD(`[${logTag}]`, logForThis);
502
+ import_error_object.ErrorObject.LOG_METHOD(`[${logTag}]`, logForThis);
490
503
  }
491
504
  return this;
492
505
  }
493
506
  toVerboseString() {
494
- return this.toDebugString() + `
495
- ${JSON.stringify(
496
- {
497
- raw: this.raw,
498
- nextErrors: this.nextErrors
499
- },
500
- null,
501
- 2
502
- )}`;
507
+ if (Array.isArray(this.nextErrors) && this.nextErrors.length > 0) {
508
+ return this.toDebugString() + `
509
+ [NEXT_ERRORS] ${JSON.stringify(this.nextErrors, null, 2)}`;
510
+ }
511
+ return this.toDebugString();
503
512
  }
504
513
  /**
505
514
  * This method allows users to check if an error is a fallback error, returned when an error could not be created from payload.
@@ -621,14 +630,16 @@ ${JSON.stringify(
621
630
  _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG = "fallback-error-object";
622
631
  // Overrides
623
632
  _ErrorObjectFromPayload.generic = () => new _ErrorObjectFromPayload({
624
- code: import_error_object2.ErrorObject.GENERIC_CODE,
625
- message: import_error_object2.ErrorObject.GENERIC_MESSAGE,
626
- tag: import_error_object2.ErrorObject.GENERIC_TAG
633
+ code: import_error_object.ErrorObject.GENERIC_CODE,
634
+ message: import_error_object.ErrorObject.GENERIC_MESSAGE,
635
+ tag: import_error_object.ErrorObject.GENERIC_TAG
627
636
  });
628
637
  var ErrorObjectFromPayload = _ErrorObjectFromPayload;
629
638
  // Annotate the CommonJS export names for ESM import in node:
630
639
  0 && (module.exports = {
631
640
  DEFAULT_BUILD_OPTIONS,
632
641
  ErrorObjectFromPayload,
633
- addPrefixPathVariants
642
+ SHOW_ERROR_LOGS,
643
+ addPrefixPathVariants,
644
+ setShowErrorLogs
634
645
  });
package/dist/index.mjs CHANGED
@@ -19,12 +19,13 @@ var __spreadValues = (a, b) => {
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
20
 
21
21
  // src/index.ts
22
- import { ErrorObject as ErrorObject2 } from "@smbcheeky/error-object";
23
-
24
- // src/builder/index.ts
25
22
  import { ErrorObject } from "@smbcheeky/error-object";
26
23
 
27
24
  // src/utils.ts
25
+ var SHOW_ERROR_LOGS = true;
26
+ var setShowErrorLogs = (value) => {
27
+ SHOW_ERROR_LOGS = value;
28
+ };
28
29
  var addPrefixPathVariants = (prefix, array) => {
29
30
  if (typeof prefix === "string") {
30
31
  return array.concat(array.map((s) => typeof s === "string" ? `${prefix}.${s}` : s));
@@ -244,7 +245,7 @@ var buildSummariesFromObject = (input, withOptions) => {
244
245
  }
245
246
  return summaries;
246
247
  } catch (generalError) {
247
- ErrorObject.SHOW_ERROR_LOGS && console.log("[ErrorObject]", "Error during buildSummariesFromObject():", generalError);
248
+ SHOW_ERROR_LOGS && console.log("[ErrorObjectFromPayload]", "Error during buildSummariesFromObject():", generalError);
248
249
  return ["generalBuildSummariesFromObjectError"];
249
250
  }
250
251
  };
@@ -263,7 +264,7 @@ var buildSummaryFromObject = (maybeObject, errorsPath, didDetectErrorsArray, wit
263
264
  }
264
265
  } catch (e) {
265
266
  }
266
- if (objectToParse === maybeObject) {
267
+ if (objectToParse === void 0) {
267
268
  objectToParse = { code: "unknown", message: maybeObject };
268
269
  }
269
270
  }
@@ -354,7 +355,7 @@ var buildSummaryFromObject = (maybeObject, errorsPath, didDetectErrorsArray, wit
354
355
  }
355
356
  };
356
357
  } catch (generalError) {
357
- ErrorObject.SHOW_ERROR_LOGS && console.log("[ErrorObject]", "Error during buildSummaryFromObject():", generalError);
358
+ SHOW_ERROR_LOGS && console.log("[ErrorObjectFromPayload]", "Error during buildSummaryFromObject():", generalError);
358
359
  return "generalBuildSummaryFromObjectError";
359
360
  }
360
361
  };
@@ -375,7 +376,13 @@ var findNestedValueForPath = (value, path) => {
375
376
  };
376
377
 
377
378
  // src/index.ts
378
- var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2 {
379
+ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject {
380
+ static get SHOW_ERROR_LOGS() {
381
+ return SHOW_ERROR_LOGS;
382
+ }
383
+ static set SHOW_ERROR_LOGS(value) {
384
+ setShowErrorLogs(value);
385
+ }
379
386
  constructor(props, withOptions) {
380
387
  var _a, _b, _c, _d;
381
388
  if ("code" in props && props.code !== void 0 && props.code !== null && typeof props.code === "string" && "message" in props && props.message !== void 0 && props.message !== null && typeof props.message === "string") {
@@ -388,7 +395,7 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2
388
395
  } catch (error) {
389
396
  super({
390
397
  code: "INT-1",
391
- message: `Error during checkInputForInitialObject(). Details: ${(_b = (_a = error == null ? void 0 : error.toString) == null ? void 0 : _a.call(error)) != null ? _b : ErrorObject2.GENERIC_MESSAGE}}`,
398
+ message: `Error during checkInputForInitialObject(). Details: ${(_b = (_a = error == null ? void 0 : error.toString) == null ? void 0 : _a.call(error)) != null ? _b : ErrorObject.GENERIC_MESSAGE}`,
392
399
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
393
400
  raw: {
394
401
  error
@@ -398,8 +405,8 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2
398
405
  }
399
406
  if (checksFailed !== void 0) {
400
407
  super({
401
- code: ErrorObject2.GENERIC_CODE,
402
- message: ErrorObject2.GENERIC_MESSAGE,
408
+ code: ErrorObject.GENERIC_CODE,
409
+ message: ErrorObject.GENERIC_MESSAGE,
403
410
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
404
411
  raw: {
405
412
  processingErrors: [{ errorCode: checksFailed, summary: void 0 }]
@@ -430,8 +437,8 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2
430
437
  }
431
438
  }
432
439
  super({
433
- code: ErrorObject2.GENERIC_CODE,
434
- message: ErrorObject2.GENERIC_MESSAGE,
440
+ code: ErrorObject.GENERIC_CODE,
441
+ message: ErrorObject.GENERIC_MESSAGE,
435
442
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
436
443
  raw: {
437
444
  processingErrors: processingErrors.length > 0 ? processingErrors : void 0,
@@ -441,7 +448,7 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2
441
448
  } catch (error) {
442
449
  super({
443
450
  code: "INT-2",
444
- message: `Error during processErrorObjectResult(). Details: ${(_d = (_c = error == null ? void 0 : error.toString) == null ? void 0 : _c.call(error)) != null ? _d : ErrorObject2.GENERIC_MESSAGE}}`,
451
+ message: `Error during processErrorObjectResult(). Details: ${(_d = (_c = error == null ? void 0 : error.toString) == null ? void 0 : _c.call(error)) != null ? _d : ErrorObject.GENERIC_MESSAGE}`,
445
452
  tag: _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG,
446
453
  raw: {
447
454
  error
@@ -450,33 +457,33 @@ var _ErrorObjectFromPayload = class _ErrorObjectFromPayload extends ErrorObject2
450
457
  }
451
458
  }
452
459
  }
460
+ verboseLog(logTag) {
461
+ return this._log(logTag, "verbose");
462
+ }
453
463
  _log(logTag, logLevel) {
464
+ if (!ErrorObject.LOG_METHOD) return this;
454
465
  const logForThis = logLevel === "verbose" ? this.toVerboseString() : logLevel === "debug" ? this.toDebugString() : this.toString();
455
466
  if (Array.isArray(this.nextErrors) && this.nextErrors.length > 0) {
456
467
  let row = 1;
457
- ErrorObject2.LOG_METHOD && typeof ErrorObject2.LOG_METHOD === "function" && ErrorObject2.LOG_METHOD(`[${logTag}][${row}]`, logForThis);
468
+ ErrorObject.LOG_METHOD(`[${logTag}][${row}]`, logForThis);
458
469
  for (const error of this.nextErrors) {
459
470
  row++;
460
- ErrorObject2.LOG_METHOD && typeof ErrorObject2.LOG_METHOD === "function" && ErrorObject2.LOG_METHOD(
471
+ ErrorObject.LOG_METHOD(
461
472
  `[${logTag}][${row}]`,
462
473
  logLevel === "verbose" ? error.toVerboseString() : logLevel === "debug" ? error.toDebugString() : error.toString()
463
474
  );
464
475
  }
465
476
  } else {
466
- ErrorObject2.LOG_METHOD && typeof ErrorObject2.LOG_METHOD === "function" && ErrorObject2.LOG_METHOD(`[${logTag}]`, logForThis);
477
+ ErrorObject.LOG_METHOD(`[${logTag}]`, logForThis);
467
478
  }
468
479
  return this;
469
480
  }
470
481
  toVerboseString() {
471
- return this.toDebugString() + `
472
- ${JSON.stringify(
473
- {
474
- raw: this.raw,
475
- nextErrors: this.nextErrors
476
- },
477
- null,
478
- 2
479
- )}`;
482
+ if (Array.isArray(this.nextErrors) && this.nextErrors.length > 0) {
483
+ return this.toDebugString() + `
484
+ [NEXT_ERRORS] ${JSON.stringify(this.nextErrors, null, 2)}`;
485
+ }
486
+ return this.toDebugString();
480
487
  }
481
488
  /**
482
489
  * This method allows users to check if an error is a fallback error, returned when an error could not be created from payload.
@@ -598,13 +605,15 @@ ${JSON.stringify(
598
605
  _ErrorObjectFromPayload.DEFAULT_FALLBACK_TAG = "fallback-error-object";
599
606
  // Overrides
600
607
  _ErrorObjectFromPayload.generic = () => new _ErrorObjectFromPayload({
601
- code: ErrorObject2.GENERIC_CODE,
602
- message: ErrorObject2.GENERIC_MESSAGE,
603
- tag: ErrorObject2.GENERIC_TAG
608
+ code: ErrorObject.GENERIC_CODE,
609
+ message: ErrorObject.GENERIC_MESSAGE,
610
+ tag: ErrorObject.GENERIC_TAG
604
611
  });
605
612
  var ErrorObjectFromPayload = _ErrorObjectFromPayload;
606
613
  export {
607
614
  DEFAULT_BUILD_OPTIONS,
608
615
  ErrorObjectFromPayload,
609
- addPrefixPathVariants
616
+ SHOW_ERROR_LOGS,
617
+ addPrefixPathVariants,
618
+ setShowErrorLogs
610
619
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@smbcheeky/error-object-from-payload",
3
3
  "description": "Create ErrorObjects from any payload with simple rules and benefit from step-to-step debugging logs for the entire process.",
4
- "version": "1.2.0",
4
+ "version": "1.2.1",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
@@ -12,7 +12,7 @@
12
12
  "lint": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@smbcheeky/error-object": "1.2.0"
15
+ "@smbcheeky/error-object": "1.2.1"
16
16
  },
17
17
  "devDependencies": {
18
18
  "tsup": "8.3.5",