Skip to content

Commit 704a227

Browse files
committed
Refactor error handling in Entries, Entry, and Query classes to utilize centralized error messages for improved consistency and clarity.
1 parent 6ad194b commit 704a227

File tree

9 files changed

+122
-72
lines changed

9 files changed

+122
-72
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@ export type { ImageTransform } from './lib/image-transform';
1111
export type { AssetQuery } from './lib/asset-query';
1212
export type { TaxonomyQuery } from './lib/taxonomy-query';
1313
export type { ContentTypeQuery } from './lib/contenttype-query';
14+
export { ErrorMessages, ErrorCode } from './lib/error-messages';
1415

1516
export default contentstack;

src/lib/entries.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Query } from './query';
33
import { BaseQuery } from './base-query';
44
import { FindResponse } from './types';
55
import { encodeQueryParams } from './utils';
6+
import { ErrorMessages } from './error-messages';
67

78
export class Entries extends BaseQuery {
89
private _contentTypeUid: string;
@@ -150,7 +151,7 @@ export class Entries extends BaseQuery {
150151
(this._queryParams['include[]'] as string[]).push(...(Array.isArray(value) ? value : [value]));
151152
});
152153
} else {
153-
console.error("Invalid argument. Provide a string or an array and try again.");
154+
console.error(ErrorMessages.INVALID_ARGUMENT_STRING_OR_ARRAY);
154155
}
155156
return this;
156157
}

src/lib/entry.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AxiosInstance, getData } from '@contentstack/core';
2+
import { ErrorMessages } from './error-messages';
23

34
interface EntryResponse<T> {
45
entry: T;
@@ -112,7 +113,7 @@ export class Entry {
112113
(this._queryParams['include[]'] as string[]).push(...(Array.isArray(value) ? value : [value]));
113114
});
114115
} else {
115-
console.error("Invalid argument. Provide a string or an array and try again.");
116+
console.error(ErrorMessages.INVALID_ARGUMENT_STRING_OR_ARRAY);
116117
}
117118
return this;
118119
}

src/lib/error-messages.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Centralized error messages for the Contentstack SDK
3+
* This file contains all user-facing error messages used throughout the SDK
4+
*/
5+
6+
export const ErrorMessages = {
7+
// Field/Key validation errors
8+
INVALID_FIELD_UID: 'Invalid fieldUid. Provide an alphanumeric field UID and try again.',
9+
INVALID_KEY: 'Invalid key. Provide an alphanumeric key and try again.',
10+
INVALID_REFERENCE_UID: (uid: string) => `Invalid referenceUid: ${uid}. Must be alphanumeric.`,
11+
12+
// Value validation errors
13+
INVALID_VALUE_STRING_OR_NUMBER: 'Invalid value. Provide a string or number and try again.',
14+
INVALID_VALUE_ARRAY: 'Invalid value. Provide an array of strings, numbers, or booleans and try again.',
15+
INVALID_ARGUMENT_STRING_OR_ARRAY: 'Invalid argument. Provide a string or an array and try again.',
16+
17+
// Storage errors
18+
MISSING_CUSTOM_STORAGE: 'Missing storage for customStorage. Provide a storage object with get, set, and remove methods and try again.',
19+
20+
// Regex validation errors
21+
INVALID_REGEX_PATTERN: 'Invalid regexPattern: Must be a valid regular expression',
22+
23+
// Slack/Integration errors (for future use if sanity-report-ts-sdk.js is added)
24+
SLACK_MESSAGE_FAILED: (details?: string) =>
25+
`Failed to send Slack message. Check the SLACK_WEBHOOK_URL and SLACK_CHANNEL configuration and try again.${details ? ` Details: ${details}` : ''}`,
26+
SLACK_FAILURE_DETAILS_FAILED: (details?: string) =>
27+
`Failed to send failure details to Slack. Verify SLACK_WEBHOOK_URL, SLACK_CHANNEL, and SLACK_TOKEN settings and try again.${details ? ` Details: ${details}` : ''}`,
28+
} as const;
29+
30+
/**
31+
* Error codes for programmatic error handling
32+
*/
33+
export enum ErrorCode {
34+
INVALID_FIELD_UID = 'INVALID_FIELD_UID',
35+
INVALID_KEY = 'INVALID_KEY',
36+
INVALID_REFERENCE_UID = 'INVALID_REFERENCE_UID',
37+
INVALID_VALUE = 'INVALID_VALUE',
38+
INVALID_ARGUMENT = 'INVALID_ARGUMENT',
39+
MISSING_STORAGE = 'MISSING_STORAGE',
40+
INVALID_REGEX = 'INVALID_REGEX',
41+
SLACK_ERROR = 'SLACK_ERROR',
42+
}
43+

src/lib/query.ts

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { AxiosInstance, getData } from '@contentstack/core';
22
import { BaseQuery } from './base-query';
33
import { BaseQueryParameters, QueryOperation, QueryOperator, TaxonomyQueryOperation, params, queryParams, FindResponse } from './types';
44
import { encodeQueryParams } from './utils';
5+
import { ErrorMessages } from './error-messages';
56

67
export class Query extends BaseQuery {
78
private _contentTypeUid?: string;
@@ -73,7 +74,7 @@ export class Query extends BaseQuery {
7374
additionalData?: object
7475
): Query {
7576
if (!this.isValidAlphanumeric(fieldUid)) {
76-
console.error("Invalid fieldUid. Provide an alphanumeric field UID and try again.");
77+
console.error(ErrorMessages.INVALID_FIELD_UID);
7778
return this;
7879
}
7980
if (queryOperation == QueryOperation.EQUALS) {
@@ -102,11 +103,11 @@ export class Query extends BaseQuery {
102103
*/
103104
regex(fieldUid: string, regexPattern: string, options?: string): Query {
104105
if (!this.isValidAlphanumeric(fieldUid)) {
105-
console.error("Invalid fieldUid. Provide an alphanumeric field UID and try again.");
106+
console.error(ErrorMessages.INVALID_FIELD_UID);
106107
return this;
107108
}
108109
if (!this.isValidRegexPattern(regexPattern)) {
109-
throw new Error("Invalid regexPattern: Must be a valid regular expression");
110+
throw new Error(ErrorMessages.INVALID_REGEX_PATTERN);
110111
}
111112
else {
112113
this._parameters[fieldUid] = { $regex: regexPattern };
@@ -134,7 +135,7 @@ export class Query extends BaseQuery {
134135
whereIn(referenceUid: string, queryInstance: Query): Query {
135136
// eslint-disable-next-line @typescript-eslint/naming-convention, prettier/prettier
136137
if (!this.isValidAlphanumeric(referenceUid)) {
137-
throw new Error("Invalid referenceUid: Must be alphanumeric.");
138+
throw new Error(ErrorMessages.INVALID_REFERENCE_UID(referenceUid));
138139
}
139140
this._parameters[referenceUid] = { '$in_query': queryInstance._parameters };
140141
return this;
@@ -159,7 +160,7 @@ export class Query extends BaseQuery {
159160
whereNotIn(referenceUid: string, queryInstance: Query): Query {
160161
// eslint-disable-next-line @typescript-eslint/naming-convention, prettier/prettier
161162
if (!this.isValidAlphanumeric(referenceUid)) {
162-
throw new Error("Invalid referenceUid: Must be alphanumeric.");
163+
throw new Error(ErrorMessages.INVALID_REFERENCE_UID(referenceUid));
163164
}
164165
this._parameters[referenceUid] = { '$nin_query': queryInstance._parameters };
165166
return this;
@@ -226,11 +227,11 @@ export class Query extends BaseQuery {
226227
*/
227228
containedIn(key: string, value: (string | number | boolean)[]): Query {
228229
if (!this.isValidAlphanumeric(key)) {
229-
console.error("Invalid key. Provide an alphanumeric key and try again.");
230+
console.error(ErrorMessages.INVALID_KEY);
230231
return this;
231232
}
232233
if (!this.isValidValue(value)) {
233-
console.error("Invalid value. Provide an array of strings, numbers, or booleans and try again.");
234+
console.error(ErrorMessages.INVALID_VALUE_ARRAY);
234235
return this;
235236
}
236237
this._parameters[key] = { '$in': value };
@@ -252,11 +253,11 @@ export class Query extends BaseQuery {
252253
*/
253254
notContainedIn(key: string, value: (string | number | boolean)[]): Query {
254255
if (!this.isValidAlphanumeric(key)) {
255-
console.error("Invalid key. Provide an alphanumeric key and try again.");
256+
console.error(ErrorMessages.INVALID_KEY);
256257
return this;
257258
}
258259
if (!this.isValidValue(value)) {
259-
console.error("Invalid value. Provide an array of strings, numbers, or booleans and try again.");
260+
console.error(ErrorMessages.INVALID_VALUE_ARRAY);
260261
return this;
261262
}
262263
this._parameters[key] = { '$nin': value };
@@ -278,7 +279,7 @@ export class Query extends BaseQuery {
278279
*/
279280
exists(key: string): Query {
280281
if (!this.isValidAlphanumeric(key)) {
281-
console.error("Invalid key. Provide an alphanumeric key and try again.");
282+
console.error(ErrorMessages.INVALID_KEY);
282283
return this;
283284
}
284285
this._parameters[key] = { '$exists': true };
@@ -300,7 +301,7 @@ export class Query extends BaseQuery {
300301
*/
301302
notExists(key: string): Query {
302303
if (!this.isValidAlphanumeric(key)) {
303-
console.error("Invalid key. Provide an alphanumeric key and try again.");
304+
console.error(ErrorMessages.INVALID_KEY);
304305
return this;
305306
}
306307
this._parameters[key] = { '$exists': false };
@@ -367,11 +368,11 @@ export class Query extends BaseQuery {
367368
*/
368369
equalTo(key: string, value: string | number | boolean): Query {
369370
if (!this.isValidAlphanumeric(key)) {
370-
console.error("Invalid key. Provide an alphanumeric key and try again.");
371+
console.error(ErrorMessages.INVALID_KEY);
371372
return this;
372373
}
373374
if (typeof value !== 'string' && typeof value !== 'number') {
374-
console.error("Invalid value. Provide a string or number and try again.");
375+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
375376
return this;
376377
}
377378
this._parameters[key] = value;
@@ -392,11 +393,11 @@ export class Query extends BaseQuery {
392393
*/
393394
notEqualTo(key: string, value: string | number | boolean): Query {
394395
if (!this.isValidAlphanumeric(key)) {
395-
console.error("Invalid key. Provide an alphanumeric key and try again.");
396+
console.error(ErrorMessages.INVALID_KEY);
396397
return this;
397398
}
398399
if (typeof value !== 'string' && typeof value !== 'number') {
399-
console.error("Invalid value. Provide a string or number and try again.");
400+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
400401
return this;
401402
}
402403
this._parameters[key] = { '$ne': value };
@@ -418,7 +419,7 @@ export class Query extends BaseQuery {
418419
*/
419420
referenceIn(key: string, query: Query): Query {
420421
if (!this.isValidAlphanumeric(key)) {
421-
console.error("Invalid key. Provide an alphanumeric key and try again.");
422+
console.error(ErrorMessages.INVALID_KEY);
422423
return this;
423424
}
424425
this._parameters[key] = { '$in_query': query._parameters }
@@ -440,7 +441,7 @@ export class Query extends BaseQuery {
440441
*/
441442
referenceNotIn(key: string, query: Query): Query {
442443
if (!this.isValidAlphanumeric(key)) {
443-
console.error("Invalid key. Provide an alphanumeric key and try again.");
444+
console.error(ErrorMessages.INVALID_KEY);
444445
return this;
445446
}
446447
this._parameters[key] = { '$nin_query': query._parameters }
@@ -462,7 +463,7 @@ export class Query extends BaseQuery {
462463
*/
463464
tags(values: (string | number | boolean)[]): Query {
464465
if (!this.isValidValue(values)) {
465-
console.error("Invalid value. Provide an array of strings, numbers, or booleans and try again.");
466+
console.error(ErrorMessages.INVALID_VALUE_ARRAY);
466467
return this;
467468
}
468469
this._parameters['tags'] = values;
@@ -484,7 +485,7 @@ export class Query extends BaseQuery {
484485
*/
485486
search(key: string): Query {
486487
if (!this.isValidAlphanumeric(key)) {
487-
console.error("Invalid key. Provide an alphanumeric key and try again.");
488+
console.error(ErrorMessages.INVALID_KEY);
488489
return this;
489490
}
490491
this._queryParams['typeahead'] = key
@@ -506,11 +507,11 @@ export class Query extends BaseQuery {
506507
*/
507508
lessThan(key: string, value: (string | number)): Query {
508509
if (!this.isValidAlphanumeric(key)) {
509-
console.error("Invalid key. Provide an alphanumeric key and try again.");
510+
console.error(ErrorMessages.INVALID_KEY);
510511
return this;
511512
}
512513
if (typeof value !== 'string' && typeof value !== 'number') {
513-
console.error("Invalid value. Provide a string or number and try again.");
514+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
514515
return this;
515516
}
516517

@@ -533,11 +534,11 @@ export class Query extends BaseQuery {
533534
*/
534535
lessThanOrEqualTo(key: string, value: (string | number)): Query {
535536
if (!this.isValidAlphanumeric(key)) {
536-
console.error("Invalid key. Provide an alphanumeric key and try again.");
537+
console.error(ErrorMessages.INVALID_KEY);
537538
return this;
538539
}
539540
if (typeof value !== 'string' && typeof value !== 'number') {
540-
console.error("Invalid value. Provide a string or number and try again.");
541+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
541542
return this;
542543
}
543544
this._parameters[key] = { '$lte': value };
@@ -559,11 +560,11 @@ export class Query extends BaseQuery {
559560
*/
560561
greaterThan(key: string, value: (string | number)): Query {
561562
if (!this.isValidAlphanumeric(key)) {
562-
console.error("Invalid key. Provide an alphanumeric key and try again.");
563+
console.error(ErrorMessages.INVALID_KEY);
563564
return this;
564565
}
565566
if (typeof value !== 'string' && typeof value !== 'number') {
566-
console.error("Invalid value. Provide a string or number and try again.");
567+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
567568
return this;
568569
}
569570
this._parameters[key] = { '$gt': value };
@@ -585,11 +586,11 @@ export class Query extends BaseQuery {
585586
*/
586587
greaterThanOrEqualTo(key: string, value: (string | number)): Query {
587588
if (!this.isValidAlphanumeric(key)) {
588-
console.error("Invalid key. Provide an alphanumeric key and try again.");
589+
console.error(ErrorMessages.INVALID_KEY);
589590
return this;
590591
}
591592
if (typeof value !== 'string' && typeof value !== 'number') {
592-
console.error("Invalid value. Provide a string or number and try again.");
593+
console.error(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
593594
return this;
594595
}
595596
this._parameters[key] = { '$gte': value };

src/persistance/persistance-store.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { localStorage } from './storages/local-storage';
33
import { memoryStorage } from './storages/memory-storage';
44
import { Storage } from './types/storage';
55
import { StorageType } from './types/storage-type';
6+
import { ErrorMessages } from '../lib/error-messages';
67

78
export class PersistanceStore {
89
protected store: Storage = localStorage;
@@ -33,7 +34,7 @@ export class PersistanceStore {
3334
break;
3435
case 'customStorage':
3536
if (!store) {
36-
throw new TypeError('Missing storage for customStorage. Provide a storage object with get, set, and remove methods and try again.');
37+
throw new TypeError(ErrorMessages.MISSING_CUSTOM_STORAGE);
3738
} else {
3839
this.store = store;
3940
}

test/unit/content-validation-comprehensive.spec.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { Entries } from '../../src/lib/entries';
1010
import { GlobalField } from '../../src/lib/global-field';
1111
import { QueryOperation, QueryOperator, TaxonomyQueryOperation } from '../../src/lib/types';
1212
import { MOCK_CLIENT_OPTIONS } from '../utils/constant';
13+
import { ErrorMessages } from '../../src/lib/error-messages';
1314

1415
describe('Content Validation - Comprehensive Test Suite', () => {
1516
let client: AxiosInstance;
@@ -659,8 +660,8 @@ describe('Content Validation - Comprehensive Test Suite', () => {
659660
query.where('123invalid', QueryOperation.EQUALS, 'test');
660661

661662
// Check that console.error was called for invalid field UIDs
662-
// Note: The validation function only logs for the first invalid field encountered
663-
expect(consoleSpy).toHaveBeenCalledWith('Invalid fieldUid:', 'invalid field');
663+
expect(consoleSpy).toHaveBeenCalledWith(ErrorMessages.INVALID_FIELD_UID);
664+
expect(consoleSpy).toHaveBeenCalledTimes(3);
664665

665666
consoleSpy.mockRestore();
666667
});
@@ -694,8 +695,8 @@ describe('Content Validation - Comprehensive Test Suite', () => {
694695
expect(() => query.regex('title', '[A-Z]+')).not.toThrow();
695696

696697
// Invalid regex patterns
697-
expect(() => query.regex('title', '[a-z')).toThrow('Invalid regexPattern: Must be a valid regular expression');
698-
expect(() => query.regex('title', '*invalid')).toThrow('Invalid regexPattern: Must be a valid regular expression');
698+
expect(() => query.regex('title', '[a-z')).toThrow(ErrorMessages.INVALID_REGEX_PATTERN);
699+
expect(() => query.regex('title', '*invalid')).toThrow(ErrorMessages.INVALID_REGEX_PATTERN);
699700
});
700701

701702
it('should validate query value types', () => {
@@ -713,8 +714,8 @@ describe('Content Validation - Comprehensive Test Suite', () => {
713714
query.equalTo('title', [] as any);
714715
query.equalTo('title', {} as any);
715716

716-
expect(consoleSpy).toHaveBeenCalledWith('Invalid value (expected string or number):', []);
717-
expect(consoleSpy).toHaveBeenCalledWith('Invalid value (expected string or number):', {});
717+
expect(consoleSpy).toHaveBeenCalledWith(ErrorMessages.INVALID_VALUE_STRING_OR_NUMBER);
718+
expect(consoleSpy).toHaveBeenCalledTimes(2);
718719

719720
consoleSpy.mockRestore();
720721
});

0 commit comments

Comments
 (0)