erlc-api 3.0.0 → 3.1.0

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.
@@ -1,4 +1,5 @@
1
1
  const { BASEURL } = require("../../constants.js");
2
+ const { processError } = require("../../utils/errorHandler.js");
2
3
 
3
4
  /**
4
5
  * Executes a command on the server
@@ -9,16 +10,16 @@ const { BASEURL } = require("../../constants.js");
9
10
  module.exports = (serverToken, command) => {
10
11
  return new Promise(async (resolve, reject) => {
11
12
  // Input validation
12
- if (!serverToken || typeof serverToken !== 'string') {
13
- return reject(new Error('Server token is required and must be a string'));
13
+ if (!serverToken || typeof serverToken !== "string") {
14
+ return reject(new Error("Server token is required and must be a string"));
14
15
  }
15
16
 
16
- if (!command || typeof command !== 'string') {
17
- return reject(new Error('Command is required and must be a string'));
17
+ if (!command || typeof command !== "string") {
18
+ return reject(new Error("Command is required and must be a string"));
18
19
  }
19
20
 
20
21
  if (command.trim().length === 0) {
21
- return reject(new Error('Command cannot be empty'));
22
+ return reject(new Error("Command cannot be empty"));
22
23
  }
23
24
 
24
25
  try {
@@ -27,7 +28,12 @@ module.exports = (serverToken, command) => {
27
28
 
28
29
  // Check if global token is configured
29
30
  if (!config?.globalToken) {
30
- return reject(new Error('Global token not configured. Please initialize the client first.'));
31
+ const error = await processError(
32
+ new Error(
33
+ "Global token not configured. Please initialize the client first."
34
+ )
35
+ );
36
+ return reject(error);
31
37
  }
32
38
 
33
39
  const requestBody = JSON.stringify({ command: command.trim() });
@@ -35,7 +41,7 @@ module.exports = (serverToken, command) => {
35
41
  const res = await fetch.default(`${BASEURL}/server/command`, {
36
42
  method: "POST",
37
43
  headers: {
38
- "Authorization": config.globalToken,
44
+ Authorization: config.globalToken,
39
45
  "Server-Key": serverToken,
40
46
  "Content-Type": "application/json",
41
47
  },
@@ -44,27 +50,18 @@ module.exports = (serverToken, command) => {
44
50
  });
45
51
 
46
52
  if (!res.ok) {
47
- const errorData = await res.json().catch(() => ({ error: 'Unknown API error' }));
48
- const error = new Error(`Command execution failed: ${res.status} - ${errorData.error || res.statusText}`);
49
- error.status = res.status;
50
- error.data = errorData;
53
+ const errorData = await res
54
+ .json()
55
+ .catch(() => ({ error: "Unknown API error" }));
56
+ const error = await processError(res, errorData);
51
57
  return reject(error);
52
58
  }
53
59
 
54
60
  // Command executed successfully
55
61
  resolve(true);
56
-
57
62
  } catch (error) {
58
- // Handle different types of errors
59
- if (error.code === 'ENOTFOUND') {
60
- reject(new Error('Network error: Unable to connect to ER:LC API'));
61
- } else if (error.name === 'AbortError') {
62
- reject(new Error('Request timeout: Command took too long to execute'));
63
- } else if (error.message.includes('JSON')) {
64
- reject(new Error('Invalid command format'));
65
- } else {
66
- reject(error);
67
- }
63
+ const processedError = await processError(error);
64
+ reject(processedError);
68
65
  }
69
66
  });
70
- };
67
+ };
@@ -1,4 +1,33 @@
1
1
  declare module "erlc-api" {
2
+ // Error handling types
3
+ export class ErlcError extends Error {
4
+ code: string | number;
5
+ status?: number;
6
+ category?: string;
7
+ severity?: string;
8
+ suggestions?: string[];
9
+ retryable?: boolean;
10
+ timestamp: string;
11
+ originalError?: Error;
12
+
13
+ constructor(
14
+ message: string,
15
+ code: string | number,
16
+ status?: number,
17
+ originalError?: Error
18
+ );
19
+ toJSON(): object;
20
+ toString(): string;
21
+ }
22
+
23
+ export interface ErrorInfo {
24
+ message: string;
25
+ description: string;
26
+ category: string;
27
+ severity: string;
28
+ code?: number;
29
+ }
30
+
2
31
  export interface ClientConfig {
3
32
  globalToken: string; // The ER:LC global API token
4
33
  }
@@ -95,4 +124,4 @@ declare module "erlc-api" {
95
124
  constructor(options: ClientConfig);
96
125
  config(): ClientConfig;
97
126
  }
98
- }
127
+ }
@@ -0,0 +1,158 @@
1
+ const ErlcError = require("../errors/ErlcError.js");
2
+ const {
3
+ getErrorInfo,
4
+ getSuggestedActions,
5
+ isRetryableError,
6
+ } = require("../errors/errorCodes.js");
7
+
8
+ /**
9
+ * Handles API response errors and creates appropriate ErlcError instances
10
+ * @param {Response} response - The fetch response object
11
+ * @param {Object} errorData - The parsed error data from response
12
+ * @returns {ErlcError} Formatted ERLC error
13
+ */
14
+ function handleApiError(response, errorData) {
15
+ const status = response.status;
16
+
17
+ // Check if error data contains ERLC error code
18
+ if (errorData && typeof errorData.code === "number") {
19
+ const errorInfo = getErrorInfo(errorData.code);
20
+ const suggestions = getSuggestedActions(errorData.code);
21
+
22
+ const message = `${errorInfo.message}: ${errorInfo.description}`;
23
+ const error = new ErlcError(message, errorData.code, status);
24
+ error.category = errorInfo.category;
25
+ error.severity = errorInfo.severity;
26
+ error.suggestions = suggestions;
27
+ error.retryable = isRetryableError(errorData.code);
28
+
29
+ return error;
30
+ }
31
+
32
+ // Handle HTTP status codes when no ERLC error code is provided
33
+ let message, code;
34
+
35
+ switch (status) {
36
+ case 400:
37
+ message = "Bad Request: The request was invalid or malformed";
38
+ code = "HTTP_400";
39
+ break;
40
+ case 401:
41
+ message = "Unauthorized: Authentication failed or missing credentials";
42
+ code = "HTTP_401";
43
+ break;
44
+ case 403:
45
+ message = "Forbidden: Access denied or insufficient permissions";
46
+ code = "HTTP_403";
47
+ break;
48
+ case 404:
49
+ message = "Not Found: The requested resource was not found";
50
+ code = "HTTP_404";
51
+ break;
52
+ case 422:
53
+ message = "Unprocessable Entity: The server has no players";
54
+ code = "HTTP_422";
55
+ break;
56
+ case 429:
57
+ message = "Too Many Requests: Rate limit exceeded";
58
+ code = "HTTP_429";
59
+ break;
60
+ case 500:
61
+ message = "Internal Server Error: Problem communicating with Roblox";
62
+ code = "HTTP_500";
63
+ break;
64
+ case 502:
65
+ message = "Bad Gateway: Server received invalid response";
66
+ code = "HTTP_502";
67
+ break;
68
+ case 503:
69
+ message = "Service Unavailable: Server temporarily unavailable";
70
+ code = "HTTP_503";
71
+ break;
72
+ default:
73
+ message = `HTTP Error ${status}: ${
74
+ errorData?.error || response.statusText || "Unknown error"
75
+ }`;
76
+ code = `HTTP_${status}`;
77
+ }
78
+
79
+ const error = new ErlcError(message, code, status);
80
+ error.category = "HTTP_ERROR";
81
+ error.severity = status >= 500 ? "HIGH" : "MEDIUM";
82
+ error.retryable = [429, 500, 502, 503].includes(status);
83
+
84
+ return error;
85
+ }
86
+
87
+ /**
88
+ * Handles network and other non-API errors
89
+ * @param {Error} originalError - The original error object
90
+ * @returns {ErlcError} Formatted ERLC error
91
+ */
92
+ function handleNetworkError(originalError) {
93
+ let message, code, category;
94
+
95
+ if (originalError.code === "ENOTFOUND") {
96
+ message =
97
+ "Network Error: Unable to connect to ERLC API (DNS resolution failed)";
98
+ code = "NETWORK_DNS_ERROR";
99
+ category = "NETWORK_ERROR";
100
+ } else if (originalError.code === "ECONNREFUSED") {
101
+ message = "Network Error: Connection refused by ERLC API server";
102
+ code = "NETWORK_CONNECTION_REFUSED";
103
+ category = "NETWORK_ERROR";
104
+ } else if (
105
+ originalError.code === "ETIMEDOUT" ||
106
+ originalError.name === "AbortError"
107
+ ) {
108
+ message = "Request Timeout: API took too long to respond";
109
+ code = "REQUEST_TIMEOUT";
110
+ category = "TIMEOUT_ERROR";
111
+ } else if (originalError.message?.includes("JSON")) {
112
+ message = "Parse Error: Invalid JSON response from API";
113
+ code = "JSON_PARSE_ERROR";
114
+ category = "PARSE_ERROR";
115
+ } else {
116
+ message = `Unexpected Error: ${originalError.message}`;
117
+ code = "UNEXPECTED_ERROR";
118
+ category = "UNKNOWN_ERROR";
119
+ }
120
+
121
+ const error = new ErlcError(message, code, null, originalError);
122
+ error.category = category;
123
+ error.severity = "MEDIUM";
124
+ error.retryable = [
125
+ "NETWORK_DNS_ERROR",
126
+ "REQUEST_TIMEOUT",
127
+ "NETWORK_CONNECTION_REFUSED",
128
+ ].includes(code);
129
+
130
+ return error;
131
+ }
132
+
133
+ /**
134
+ * Main error handler that processes any error and returns a standardized ErlcError
135
+ * @param {Error|Response} error - The error to handle
136
+ * @param {Object} [errorData] - Additional error data if available
137
+ * @returns {ErlcError} Standardized ERLC error
138
+ */
139
+ async function processError(error, errorData = null) {
140
+ // If it's already an ErlcError, return as-is
141
+ if (error instanceof ErlcError) {
142
+ return error;
143
+ }
144
+
145
+ // If it's a Response object (from fetch), handle as API error
146
+ if (error && typeof error.status === "number") {
147
+ return handleApiError(error, errorData);
148
+ }
149
+
150
+ // Handle as network/system error
151
+ return handleNetworkError(error);
152
+ }
153
+
154
+ module.exports = {
155
+ handleApiError,
156
+ handleNetworkError,
157
+ processError,
158
+ };