Skip to content

Commit 072eb9b

Browse files
authored
Merge pull request #228 from contentstack/fix/DX-3455-error-message-improve
Error messages updates
2 parents a84b14c + edff5cd commit 072eb9b

17 files changed

+130
-45
lines changed

src/main/java/com/contentstack/sdk/AssetLibrary.java

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,11 @@ public AssetLibrary addParam(@NotNull String paramKey, @NotNull Object paramValu
179179
if (isValidKey(paramKey) && isValidValue(paramValue)) {
180180
urlQueries.put(paramKey, paramValue);
181181
} else {
182-
logger.warning("Invalid key or value");
182+
if (!isValidKey(paramKey)) {
183+
logger.warning(ErrorMessages.INVALID_PARAMETER_KEY);
184+
} else {
185+
logger.warning(ErrorMessages.INVALID_PARAMETER_VALUE);
186+
}
183187
}
184188
return this;
185189
}
@@ -310,9 +314,10 @@ public void getResultObject(List<Object> objects, JSONObject jsonObject, boolean
310314

311315
List<Asset> assets = new ArrayList<>();
312316

313-
// if (objects == null || objects.isEmpty()) {
314-
// System.out.println("Objects list is null or empty");
315-
// }
317+
if (objects == null || objects.isEmpty()) {
318+
logger.warning(ErrorMessages.MISSING_ASSETS_LIST);
319+
return;
320+
}
316321

317322
if (objects != null && !objects.isEmpty()) {
318323
for (Object object : objects) {
@@ -328,9 +333,9 @@ public void getResultObject(List<Object> objects, JSONObject jsonObject, boolean
328333
assets.add(asset);
329334
}
330335
}
331-
// else {
332-
// System.out.println("Object is not an instance of AssetModel");
333-
// }
336+
else {
337+
logger.warning(ErrorMessages.INVALID_OBJECT_TYPE_ASSET_MODEL);
338+
}
334339

335340
if (callback != null) {
336341
callback.onRequestFinish(ResponseType.NETWORK, assets);
@@ -351,7 +356,11 @@ public AssetLibrary where(String key, String value) {
351356
queryParams.put(key,value);
352357
urlQueries.put("query", queryParams);
353358
} else {
354-
throw new IllegalArgumentException("Invalid key or value");
359+
if (!isValidKey(key)) {
360+
throw new IllegalArgumentException(ErrorMessages.INVALID_PARAMETER_KEY);
361+
} else {
362+
throw new IllegalArgumentException(ErrorMessages.INVALID_PARAMETER_VALUE);
363+
}
355364
}
356365
return this;
357366
}

src/main/java/com/contentstack/sdk/AssetsModel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public AssetsModel(JSONObject response) {
3131
List<?> assetsList = (List<?>) rawAssets;
3232
listResponse = new JSONArray(assetsList); // Convert to JSONArray
3333
} else if (rawAssets != null) {
34-
throw new IllegalArgumentException("Invalid type for 'assets' key: " + rawAssets.getClass().getName());
34+
throw new IllegalArgumentException(ErrorMessages.INVALID_ASSETS_TYPE);
3535
}
3636
if (listResponse != null) {
3737
listResponse.forEach(model -> {

src/main/java/com/contentstack/sdk/CSBackgroundTask.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ protected void checkHeader(@NotNull Map<String, Object> headers) {
9393
final Logger logger = Logger.getLogger("CSBackgroundTask");
9494
if (headers.size() == 0) {
9595
try {
96-
throw new IllegalAccessException("CSBackgroundTask Header Exception");
96+
throw new IllegalAccessException(ErrorMessages.MISSING_REQUEST_HEADERS);
9797
} catch (IllegalAccessException e) {
9898
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
9999
}

src/main/java/com/contentstack/sdk/CSHttpConnection.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ private String getParams(HashMap<String, Object> params) {
158158
urlParams += urlParams.equals("?") ? key + "=" + value : "&" + key + "=" + value;
159159
}
160160
} catch (Exception e1) {
161-
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
161+
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e1);
162162
}
163163
}
164164
return urlParams;
@@ -187,7 +187,7 @@ public void send() {
187187
try {
188188
getService(url);
189189
} catch (IOException | JSONException e) {
190-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
190+
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e);
191191
}
192192
}
193193

@@ -238,7 +238,7 @@ private void getService(String requestUrl) throws IOException {
238238
connectionRequest.onRequestFinished(CSHttpConnection.this);
239239
} catch (JSONException e) {
240240
// Handle non-JSON response
241-
setError("Invalid JSON response");
241+
setError(ErrorMessages.INVALID_JSON_RESPONSE);
242242
}
243243
} else {
244244
assert response.errorBody() != null;

src/main/java/com/contentstack/sdk/ContentType.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public class ContentType {
4040
public JSONObject contentTypeData;
4141

4242
protected ContentType() throws IllegalAccessException {
43-
throw new IllegalAccessException("Can Not Access Private Modifier");
43+
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_CONTENT_TYPE);
4444
}
4545

4646
protected ContentType(String contentTypeUid) {
@@ -158,7 +158,7 @@ public void fetch(@NotNull JSONObject params, final ContentTypesCallback callbac
158158
}
159159
params.put("environment", headers.get("environment"));
160160
if (contentTypeUid == null || contentTypeUid.isEmpty()) {
161-
throw new IllegalAccessException("contentTypeUid is required");
161+
throw new IllegalAccessException(ErrorMessages.CONTENT_TYPE_UID_REQUIRED);
162162
}
163163
fetchContentTypes(urlString, params, headers, callback);
164164
}

src/main/java/com/contentstack/sdk/ContentTypesModel.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public void setJSON(JSONObject responseJSON) {
2929
try {
3030
this.response = new JSONObject((LinkedHashMap<?, ?>) responseJSON.get(ctKey));
3131
} catch (Exception e) {
32-
System.err.println("Error processing 'content_type': " + e.getMessage());
32+
System.err.println(ErrorMessages.INVALID_CONTENT_TYPE_DATA + " Technical details: " + e.getMessage());
3333
}
3434
}
3535
String ctListKey = "content_types";
@@ -44,14 +44,14 @@ public void setJSON(JSONObject responseJSON) {
4444
JSONObject jsonModel = new JSONObject((LinkedHashMap<?, ?>) model);
4545
objectList.add(jsonModel);
4646
} else {
47-
System.err.println("Invalid type in 'content_types' list. Expected LinkedHashMap.");
47+
System.err.println(ErrorMessages.INVALID_CONTENT_TYPES_LIST);
4848
}
4949
});
5050
}
5151
this.response = new JSONArray(objectList);
5252
this.responseJSONArray = new JSONArray(objectList);
5353
} catch (Exception e) {
54-
System.err.println("Error processing 'content_types': " + e.getMessage());
54+
System.err.println(ErrorMessages.INVALID_CONTENT_TYPE_DATA + " Technical details: " + e.getMessage());
5555
}
5656
}
5757
}

src/main/java/com/contentstack/sdk/Contentstack.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public class Contentstack {
1919

2020
// Modifier Protected
2121
protected Contentstack() throws IllegalAccessException {
22-
throw new IllegalAccessException("Can Not Access Private Modifier");
22+
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_CONTENTSTACK);
2323
}
2424

2525
/**
@@ -88,13 +88,13 @@ private static void validateCredentials(String stackApiKey, String deliveryToken
8888
Objects.requireNonNull(environment, "Environment can not be null");
8989

9090
if (stackApiKey.isEmpty()) {
91-
throw new IllegalAccessException("API Key can not be empty");
91+
throw new IllegalAccessException(ErrorMessages.MISSING_API_KEY);
9292
}
9393
if (deliveryToken.isEmpty()) {
94-
throw new IllegalAccessException("Delivery Token can not be empty");
94+
throw new IllegalAccessException(ErrorMessages.MISSING_DELIVERY_TOKEN);
9595
}
9696
if (environment.isEmpty()) {
97-
throw new IllegalAccessException("Environment can not be empty");
97+
throw new IllegalAccessException(ErrorMessages.MISSING_ENVIRONMENT);
9898
}
9999
}
100100

src/main/java/com/contentstack/sdk/EntriesModel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ protected EntriesModel(JSONObject responseJSON) {
3333
}
3434
} catch (Exception e) {
3535
Logger logger = Logger.getLogger(EntriesModel.class.getSimpleName());
36-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
36+
logger.log(Level.SEVERE, ErrorMessages.ENTRIES_PROCESSING_FAILED, e);
3737
}
3838

3939
}

src/main/java/com/contentstack/sdk/Entry.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public class Entry {
4545
protected String rteContent = null;
4646

4747
protected Entry() throws IllegalAccessException {
48-
throw new IllegalAccessException("Can Not Access Private Modifier");
48+
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_ENTRY);
4949
}
5050

5151
protected Entry(String contentTypeName) {
@@ -503,7 +503,7 @@ public Calendar getDate(@NotNull String key) {
503503
String value = getString(key);
504504
return Constants.parseDate(value, null);
505505
} catch (Exception e) {
506-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
506+
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
507507
}
508508
return null;
509509
}
@@ -525,7 +525,7 @@ public Calendar getCreateAt() {
525525
String value = getString("created_at");
526526
return Constants.parseDate(value, null);
527527
} catch (Exception e) {
528-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
528+
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
529529
}
530530
return null;
531531
}
@@ -562,7 +562,7 @@ public Calendar getUpdateAt() {
562562
String value = getString("updated_at");
563563
return Constants.parseDate(value, null);
564564
} catch (Exception e) {
565-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
565+
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
566566
}
567567
return null;
568568
}
@@ -601,7 +601,7 @@ public Calendar getDeleteAt() {
601601
String value = getString("deleted_at");
602602
return Constants.parseDate(value, null);
603603
} catch (Exception e) {
604-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
604+
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
605605
}
606606
return null;
607607
}
@@ -764,7 +764,7 @@ public List<Entry> getAllEntries(String refKey, String refContentType) {
764764
entryInstance = contentType.stackInstance.contentType(refContentType).entry();
765765
} catch (Exception e) {
766766
entryInstance = new Entry(refContentType);
767-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
767+
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
768768
}
769769
entryInstance.setUid(model.uid);
770770
entryInstance.resultJson = model.jsonObject;
@@ -928,9 +928,9 @@ public Entry exceptWithReferenceUid(@NotNull List<String> fieldUid, @NotNull Str
928928
public void fetch(EntryResultCallBack callback) {
929929
if (uid.isEmpty()) { // throws IllegalAccessException if uid is Empty
930930
try {
931-
throw new IllegalAccessException("Entry Uid is required");
931+
throw new IllegalAccessException(ErrorMessages.ENTRY_UID_REQUIRED);
932932
} catch (IllegalAccessException e) {
933-
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
933+
logger.log(Level.SEVERE, ErrorMessages.ENTRY_FETCH_FAILED, e);
934934
}
935935
}
936936
String urlString = "content_types/" + contentTypeUid + "/entries/" + uid;
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.contentstack.sdk;
2+
3+
/**
4+
* Centralized error messages for the Contentstack SDK.
5+
* This class contains all user-facing error messages to ensure consistency
6+
* and make maintenance easier.
7+
*/
8+
public final class ErrorMessages {
9+
10+
// Prevent instantiation
11+
private ErrorMessages() {
12+
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
13+
}
14+
15+
// ========== AUTHENTICATION & ACCESS ERRORS ==========
16+
17+
public static final String MISSING_API_KEY = "Missing API key. Provide a valid key from your Contentstack stack settings and try again.";
18+
public static final String MISSING_DELIVERY_TOKEN = "Missing delivery token. Provide a valid token from your Contentstack stack settings and try again.";
19+
public static final String MISSING_ENVIRONMENT = "Missing environment. Provide a valid environment name and try again.";
20+
public static final String MISSING_REQUEST_HEADERS = "Missing request headers. Provide api_key, access_token, and environment, then try again.";
21+
22+
// ========== DIRECT INSTANTIATION ERRORS ==========
23+
24+
public static final String DIRECT_INSTANTIATION_STACK = "Direct instantiation of Stack is not allowed. Use Contentstack.stack() to create an instance.";
25+
public static final String DIRECT_INSTANTIATION_CONTENTSTACK = "Direct instantiation of Stack is not allowed. Use Contentstack.stack() to create an instance.";
26+
public static final String DIRECT_INSTANTIATION_CONTENT_TYPE = "Direct instantiation of ContentType is not allowed. Use Stack.contentType(uid) to create an instance.";
27+
public static final String DIRECT_INSTANTIATION_ENTRY = "Direct instantiation of Entry is not allowed. Use ContentType.entry(uid) to create an instance.";
28+
29+
// ========== REQUIRED FIELD ERRORS ==========
30+
31+
public static final String CONTENT_TYPE_UID_REQUIRED = "Content type UID is required. Provide a valid UID and try again.";
32+
public static final String ENTRY_UID_REQUIRED = "Missing entry UID. Provide a valid UID and try again.";
33+
public static final String GLOBAL_FIELD_UID_REQUIRED = "Missing global field UID. Provide a valid UID and try again.";
34+
35+
// ========== DATA VALIDATION ERRORS ==========
36+
37+
public static final String INVALID_PARAMETER_KEY = "Invalid parameter key. Use only alphanumeric characters, underscores, and dots.";
38+
public static final String INVALID_PARAMETER_VALUE = "Invalid parameter value. Remove unsupported characters and try again.";
39+
public static final String INVALID_QUERY_URL = "Invalid query URL. Use a valid URL and try again.";
40+
public static final String INVALID_DATE_FORMAT = "Invalid date format for field. Provide the date in ISO format and try again.";
41+
42+
// ========== DATA TYPE ERRORS ==========
43+
44+
public static final String INVALID_ASSETS_TYPE = "Invalid type for 'assets' key. Provide assets as a List or ArrayList and try again.";
45+
public static final String INVALID_OBJECT_TYPE_ASSET_MODEL = "Invalid object type. Use an AssetModel object and try again.";
46+
public static final String INVALID_CONTENT_TYPE_DATA = "Invalid content type data. Provide a LinkedHashMap structure and try again.";
47+
public static final String INVALID_CONTENT_TYPES_LIST = "Invalid type in content types list. Use a LinkedHashMap and try again.";
48+
public static final String INVALID_GLOBAL_FIELD_DATA = "Invalid global field data. Provide a LinkedHashMap structure and try again.";
49+
public static final String INVALID_GLOBAL_FIELDS_LIST = "Invalid type in global fields list. Use a LinkedHashMap and try again.";
50+
51+
// ========== MISSING DATA ERRORS ==========
52+
53+
public static final String MISSING_ASSETS_LIST = "Missing assets list. Provide a valid list of assets and try again.";
54+
public static final String MISSING_JSON_OBJECT_SYNC = "Missing JSON object for sync operation. Provide a valid JSON object with sync parameters and try again.";
55+
56+
// ========== NETWORK & CONNECTION ERRORS ==========
57+
58+
public static final String URL_PARAMETER_ENCODING_FAILED = "URL parameter encoding failed. Provide a valid key and value, then try again.";
59+
public static final String LIVE_PREVIEW_URL_FAILED = "Failed to execute the Live Preview URL. Check your connection and try again.";
60+
public static final String TAXONOMY_QUERY_FAILED = "Failed to execute taxonomy query. Check your network connection and verify taxonomy parameters.";
61+
public static final String INVALID_JSON_RESPONSE = "Invalid JSON response. Check the server response format and try again.";
62+
63+
// ========== CONFIGURATION ERRORS ==========
64+
65+
public static final String MISSING_PREVIEW_TOKEN = "Missing preview token for rest-preview.contentstack.com. Set the preview token in your configuration to use Live Preview.";
66+
public static final String LIVE_PREVIEW_NOT_ENABLED = "Live Preview is not enabled in the configuration. Enable it and try again.";
67+
public static final String EMBEDDED_ITEMS_NOT_INCLUDED = "Embedded items are not included in the entry. Call includeEmbeddedItems() and try again.";
68+
69+
// ========== OPERATION ERRORS ==========
70+
71+
public static final String ENTRY_FETCH_FAILED = "Entry fetch operation failed due to missing UID. Provide a valid UID and try again.";
72+
public static final String QUERY_EXECUTION_FAILED = "Query execution failed. Check the query and try again.";
73+
public static final String ENTRIES_PROCESSING_FAILED = "Failed to process entries data. Check the entries format and try again.";
74+
public static final String GROUP_DATE_PARSING_FAILED = "Failed to parse date from group field. Provide a valid date format and try again.";
75+
public static final String QUERY_RESULT_PROCESSING_FAILED = "Failed to process query result data. Check the response format and try again.";
76+
}

0 commit comments

Comments
 (0)