Parcourir la source

Better error message when using RAW api

painor il y a 3 ans
Parent
commit
661880c894

+ 5 - 1
README.md

@@ -31,4 +31,8 @@ you can find all the requests and types at https://gram.js.org/
 
 
 ## Docs
 ## Docs
 
 
-you can find the docs at https://painor.gitbook.io/gramjs/ which has all the functions with a usage example
+you can find the docs at https://painor.gitbook.io/gramjs/ or https://gram.js.org/  which has all the functions with a usage example
+
+##Asking question
+
+If you have any question about how to use the library feel free to open a github issue or join us at the telegram group [@GramJSChat](https://t.me/gramjschat)

+ 1 - 1
gramjs/client/TelegramClient.ts

@@ -1200,7 +1200,7 @@ export class TelegramClient extends TelegramBaseClient {
                 return sender;
                 return sender;
             } catch (e) {
             } catch (e) {
                 // we can't create sender for our own main DC
                 // we can't create sender for our own main DC
-                if (e.message == "DC_ID_INVALID") {
+                if (e.errorMessage == "DC_ID_INVALID") {
                     return this._sender!;
                     return this._sender!;
                 }
                 }
                 await sender.disconnect();
                 await sender.disconnect();

+ 6 - 6
gramjs/client/auth.ts

@@ -103,7 +103,7 @@ export async function signInUser(
                 try {
                 try {
                     phoneNumber = await authParams.phoneNumber();
                     phoneNumber = await authParams.phoneNumber();
                 } catch (err) {
                 } catch (err) {
-                    if (err.message === "RESTART_AUTH_WITH_QR") {
+                    if (err.errorMessage === "RESTART_AUTH_WITH_QR") {
                         return client.signInUserWithQrCode(
                         return client.signInUserWithQrCode(
                             apiCredentials,
                             apiCredentials,
                             authParams
                             authParams
@@ -150,7 +150,7 @@ export async function signInUser(
                 phoneCode = await authParams.phoneCode(isCodeViaApp);
                 phoneCode = await authParams.phoneCode(isCodeViaApp);
             } catch (err) {
             } catch (err) {
                 // This is the support for changing phone number from the phone code screen.
                 // This is the support for changing phone number from the phone code screen.
-                if (err.message === "RESTART_AUTH") {
+                if (err.errorMessage === "RESTART_AUTH") {
                     return client.signInUser(apiCredentials, authParams);
                     return client.signInUser(apiCredentials, authParams);
                 }
                 }
             }
             }
@@ -177,7 +177,7 @@ export async function signInUser(
 
 
             return result.user;
             return result.user;
         } catch (err) {
         } catch (err) {
-            if (err.message === "SESSION_PASSWORD_NEEDED") {
+            if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
                 return client.signInWithPassword(apiCredentials, authParams);
                 return client.signInWithPassword(apiCredentials, authParams);
             } else {
             } else {
                 const shouldWeStop = await authParams.onError(err);
                 const shouldWeStop = await authParams.onError(err);
@@ -275,7 +275,7 @@ export async function signInUserWithQrCode(
     try {
     try {
         await Promise.race([updatePromise, inputPromise]);
         await Promise.race([updatePromise, inputPromise]);
     } catch (err) {
     } catch (err) {
-        if (err.message === "RESTART_AUTH") {
+        if (err.errorMessage === "RESTART_AUTH") {
             return client.signInUser(apiCredentials, authParams);
             return client.signInUser(apiCredentials, authParams);
         }
         }
 
 
@@ -312,7 +312,7 @@ export async function signInUserWithQrCode(
             }
             }
         }
         }
     } catch (err) {
     } catch (err) {
-        if (err.message === "SESSION_PASSWORD_NEEDED") {
+        if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
             return client.signInWithPassword(apiCredentials, authParams);
             return client.signInWithPassword(apiCredentials, authParams);
         }
         }
     }
     }
@@ -363,7 +363,7 @@ export async function sendCode(
             isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,
             isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,
         };
         };
     } catch (err) {
     } catch (err) {
-        if (err.message === "AUTH_RESTART") {
+        if (err.errorMessage === "AUTH_RESTART") {
             return client.sendCode(apiCredentials, phoneNumber, forceSMS);
             return client.sendCode(apiCredentials, phoneNumber, forceSMS);
         } else {
         } else {
             throw err;
             throw err;

+ 1 - 1
gramjs/client/downloads.ts

@@ -99,7 +99,7 @@ export async function downloadFile(
             client._log.debug(`Finished creating sender for ${dcId}`);
             client._log.debug(`Finished creating sender for ${dcId}`);
         } catch (e) {
         } catch (e) {
             // This should never raise
             // This should never raise
-            if (e.message === "DC_ID_INVALID") {
+            if (e.errorMessage === "DC_ID_INVALID") {
                 // Can't export a sender for the ID we are currently in
                 // Can't export a sender for the ID we are currently in
                 sender = client._sender!;
                 sender = client._sender!;
             } else {
             } else {

+ 1 - 1
gramjs/client/messages.ts

@@ -358,7 +358,7 @@ export class _IDsIter extends RequestIter {
                     })
                     })
                 );
                 );
             } catch (e) {
             } catch (e) {
-                if (e.message == "MESSAGE_IDS_EMPTY") {
+                if (e.errorMessage == "MESSAGE_IDS_EMPTY") {
                     r = new Api.messages.MessagesNotModified({
                     r = new Api.messages.MessagesNotModified({
                         count: ids.length,
                         count: ids.length,
                     });
                     });

+ 1 - 1
gramjs/client/uploads.ts

@@ -136,7 +136,7 @@ export async function uploadFile(
                 ),
                 ),
             ]);
             ]);
         } catch (err) {
         } catch (err) {
-            if (err.message === "TIMEOUT") {
+            if (err.error === "TIMEOUT") {
                 console.warn("Upload timeout. Retrying...");
                 console.warn("Upload timeout. Retrying...");
                 i -= workers;
                 i -= workers;
                 continue;
                 continue;

+ 4 - 4
gramjs/client/users.ts

@@ -40,8 +40,8 @@ export async function invoke<R extends Api.AnyRequest>(
         } catch (e) {
         } catch (e) {
             if (
             if (
                 e instanceof errors.ServerError ||
                 e instanceof errors.ServerError ||
-                e.message === "RPC_CALL_FAIL" ||
-                e.message === "RPC_MCGET_FAIL"
+                e.errorMessage === "RPC_CALL_FAIL" ||
+                e.errorMessage === "RPC_MCGET_FAIL"
             ) {
             ) {
                 client._log.warn(
                 client._log.warn(
                     `Telegram is having internal issues ${e.constructor.name}`
                     `Telegram is having internal issues ${e.constructor.name}`
@@ -333,7 +333,7 @@ export async function _getEntityFromString(
                 }
                 }
             }
             }
         } catch (e) {
         } catch (e) {
-            if (e.message === "BOT_METHOD_INVALID") {
+            if (e.errorMessage === "BOT_METHOD_INVALID") {
                 throw new Error(
                 throw new Error(
                     "Cannot get entity by phone number as a " +
                     "Cannot get entity by phone number as a " +
                         "bot (try using integer IDs, not strings)"
                         "bot (try using integer IDs, not strings)"
@@ -379,7 +379,7 @@ export async function _getEntityFromString(
                     }
                     }
                 }
                 }
             } catch (e) {
             } catch (e) {
-                if (e.message === "USERNAME_NOT_OCCUPIED") {
+                if (e.errorMessage === "USERNAME_NOT_OCCUPIED") {
                     throw new Error(`No user has "${username}" as username`);
                     throw new Error(`No user has "${username}" as username`);
                 }
                 }
                 throw e;
                 throw e;

+ 2 - 1
gramjs/errors/Common.ts

@@ -141,6 +141,7 @@ export class BadMessageError extends Error {
         64: "Invalid container.",
         64: "Invalid container.",
     };
     };
     private code: number;
     private code: number;
+    private errorMessage: string;
 
 
     constructor(request: Api.AnyRequest, code: number) {
     constructor(request: Api.AnyRequest, code: number) {
         let errorMessage =
         let errorMessage =
@@ -148,7 +149,7 @@ export class BadMessageError extends Error {
             `Unknown error code (this should not happen): ${code}.`;
             `Unknown error code (this should not happen): ${code}.`;
         errorMessage += `  Caused by ${request.className}`;
         errorMessage += `  Caused by ${request.className}`;
         super(errorMessage);
         super(errorMessage);
-        this.message = errorMessage;
+        this.errorMessage = errorMessage;
         this.code = code;
         this.code = code;
     }
     }
 }
 }

+ 14 - 12
gramjs/errors/RPCBaseErrors.ts

@@ -2,19 +2,21 @@
  * Base class for all Remote Procedure Call errors.
  * Base class for all Remote Procedure Call errors.
  */
  */
 import { Api } from "../tl";
 import { Api } from "../tl";
+import { CustomError } from 'ts-custom-error'
 
 
-export class RPCError extends Error {
+export class RPCError extends CustomError {
     protected code: number | undefined;
     protected code: number | undefined;
+    protected errorMessage: string;
 
 
     constructor(message: string, request: Api.AnyRequest, code?: number) {
     constructor(message: string, request: Api.AnyRequest, code?: number) {
         super(
         super(
-            "RPCError {0}: {1}{2}"
+            "{0}: {1}{2}"
                 .replace("{0}", code?.toString() || "")
                 .replace("{0}", code?.toString() || "")
                 .replace("{1}", message || "")
                 .replace("{1}", message || "")
                 .replace("{2}", RPCError._fmtRequest(request))
                 .replace("{2}", RPCError._fmtRequest(request))
         );
         );
         this.code = code;
         this.code = code;
-        this.message = message;
+        this.errorMessage = message;
     }
     }
 
 
     static _fmtRequest(request: Api.AnyRequest) {
     static _fmtRequest(request: Api.AnyRequest) {
@@ -34,7 +36,7 @@ export class InvalidDCError extends RPCError {
     constructor(message: string, request: Api.AnyRequest, code?: number) {
     constructor(message: string, request: Api.AnyRequest, code?: number) {
         super(message, request, code);
         super(message, request, code);
         this.code = code || 303;
         this.code = code || 303;
-        this.message = message || "ERROR_SEE_OTHER";
+        this.errorMessage = message || "ERROR_SEE_OTHER";
     }
     }
 }
 }
 
 
@@ -45,7 +47,7 @@ export class InvalidDCError extends RPCError {
  */
  */
 export class BadRequestError extends RPCError {
 export class BadRequestError extends RPCError {
     code = 400;
     code = 400;
-    message = "BAD_REQUEST";
+    errorMessage = "BAD_REQUEST";
 }
 }
 
 
 /**
 /**
@@ -54,7 +56,7 @@ export class BadRequestError extends RPCError {
  */
  */
 export class UnauthorizedError extends RPCError {
 export class UnauthorizedError extends RPCError {
     code = 401;
     code = 401;
-    message = "UNAUTHORIZED";
+    errorMessage = "UNAUTHORIZED";
 }
 }
 
 
 /**
 /**
@@ -63,7 +65,7 @@ export class UnauthorizedError extends RPCError {
  */
  */
 export class ForbiddenError extends RPCError {
 export class ForbiddenError extends RPCError {
     code = 403;
     code = 403;
-    message = "FORBIDDEN";
+    errorMessage = "FORBIDDEN";
 }
 }
 
 
 /**
 /**
@@ -71,7 +73,7 @@ export class ForbiddenError extends RPCError {
  */
  */
 export class NotFoundError extends RPCError {
 export class NotFoundError extends RPCError {
     code = 404;
     code = 404;
-    message = "NOT_FOUND";
+    errorMessage = "NOT_FOUND";
 }
 }
 
 
 /**
 /**
@@ -80,7 +82,7 @@ export class NotFoundError extends RPCError {
  */
  */
 export class AuthKeyError extends RPCError {
 export class AuthKeyError extends RPCError {
     code = 406;
     code = 406;
-    message = "AUTH_KEY";
+    errorMessage = "AUTH_KEY";
 }
 }
 
 
 /**
 /**
@@ -91,7 +93,7 @@ export class AuthKeyError extends RPCError {
  */
  */
 export class FloodError extends RPCError {
 export class FloodError extends RPCError {
     code = 420;
     code = 420;
-    message = "FLOOD";
+    errorMessage = "FLOOD";
 }
 }
 
 
 /**
 /**
@@ -101,7 +103,7 @@ export class FloodError extends RPCError {
  */
  */
 export class ServerError extends RPCError {
 export class ServerError extends RPCError {
     code = 500; // Also witnessed as -500
     code = 500; // Also witnessed as -500
-    message = "INTERNAL";
+    errorMessage = "INTERNAL";
 }
 }
 
 
 /**
 /**
@@ -110,5 +112,5 @@ export class ServerError extends RPCError {
  */
  */
 export class TimedOutError extends RPCError {
 export class TimedOutError extends RPCError {
     code = 503; // Only witnessed as -503
     code = 503; // Only witnessed as -503
-    message = "Timeout";
+    errorMessage = "Timeout";
 }
 }

+ 2 - 2
gramjs/errors/index.ts

@@ -13,6 +13,7 @@ export function RPCMessageToError(
     rpcError: Api.RpcError,
     rpcError: Api.RpcError,
     request: Api.AnyRequest
     request: Api.AnyRequest
 ) {
 ) {
+
     for (const [msgRegex, Cls] of rpcErrorRe) {
     for (const [msgRegex, Cls] of rpcErrorRe) {
         const m = rpcError.errorMessage.match(msgRegex);
         const m = rpcError.errorMessage.match(msgRegex);
         if (m) {
         if (m) {
@@ -20,8 +21,7 @@ export function RPCMessageToError(
             return new Cls({ request: request, capture: capture });
             return new Cls({ request: request, capture: capture });
         }
         }
     }
     }
-
-    return new RPCError(rpcError.errorMessage, request);
+    return new RPCError(rpcError.errorMessage, request, rpcError.errorCode);
 }
 }
 
 
 export * from "./Common";
 export * from "./Common";

+ 2 - 2
gramjs/tl/custom/messageButton.ts

@@ -70,7 +70,7 @@ export class MessageButton {
             try {
             try {
                 return await this._client.invoke(request);
                 return await this._client.invoke(request);
             } catch (e) {
             } catch (e) {
-                if (e.messages == "BOT_RESPONSE_TIMEOUT") {
+                if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {
                     return null;
                     return null;
                 }
                 }
                 throw e;
                 throw e;
@@ -94,7 +94,7 @@ export class MessageButton {
             try {
             try {
                 return await this._client.invoke(request);
                 return await this._client.invoke(request);
             } catch (e) {
             } catch (e) {
-                if (e.messages == "BOT_RESPONSE_TIMEOUT") {
+                if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {
                     return null;
                     return null;
                 }
                 }
                 throw e;
                 throw e;

+ 14 - 0
package-lock.json

@@ -22,6 +22,7 @@
         "path-browserify": "^1.0.1",
         "path-browserify": "^1.0.1",
         "process": "^0.11.10",
         "process": "^0.11.10",
         "store2": "^2.12.0",
         "store2": "^2.12.0",
+        "ts-custom-error": "^3.2.0",
         "ts-mixer": "^5.4.0",
         "ts-mixer": "^5.4.0",
         "util": "^0.12.4",
         "util": "^0.12.4",
         "websocket": "^1.0.33"
         "websocket": "^1.0.33"
@@ -10550,6 +10551,14 @@
         "node": ">=8"
         "node": ">=8"
       }
       }
     },
     },
+    "node_modules/ts-custom-error": {
+      "version": "3.2.0",
+      "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.2.0.tgz",
+      "integrity": "sha512-cBvC2QjtvJ9JfWLvstVnI45Y46Y5dMxIaG1TDMGAD/R87hpvqFL+7LhvUDhnRCfOnx/xitollFWWvUKKKhbN0A==",
+      "engines": {
+        "node": ">=8.0.0"
+      }
+    },
     "node_modules/ts-loader": {
     "node_modules/ts-loader": {
       "version": "8.0.16",
       "version": "8.0.16",
       "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.0.16.tgz",
       "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.0.16.tgz",
@@ -20709,6 +20718,11 @@
         "punycode": "^2.1.1"
         "punycode": "^2.1.1"
       }
       }
     },
     },
+    "ts-custom-error": {
+      "version": "3.2.0",
+      "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.2.0.tgz",
+      "integrity": "sha512-cBvC2QjtvJ9JfWLvstVnI45Y46Y5dMxIaG1TDMGAD/R87hpvqFL+7LhvUDhnRCfOnx/xitollFWWvUKKKhbN0A=="
+    },
     "ts-loader": {
     "ts-loader": {
       "version": "8.0.16",
       "version": "8.0.16",
       "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.0.16.tgz",
       "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.0.16.tgz",

+ 2 - 1
package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "telegram",
   "name": "telegram",
-  "version": "1.7.27",
+  "version": "1.8.0",
   "description": "NodeJS MTProto API Telegram client library,",
   "description": "NodeJS MTProto API Telegram client library,",
   "main": "index.js",
   "main": "index.js",
   "types": "index.d.ts",
   "types": "index.d.ts",
@@ -54,6 +54,7 @@
     "path-browserify": "^1.0.1",
     "path-browserify": "^1.0.1",
     "process": "^0.11.10",
     "process": "^0.11.10",
     "store2": "^2.12.0",
     "store2": "^2.12.0",
+    "ts-custom-error": "^3.2.0",
     "ts-mixer": "^5.4.0",
     "ts-mixer": "^5.4.0",
     "util": "^0.12.4",
     "util": "^0.12.4",
     "websocket": "^1.0.33"
     "websocket": "^1.0.33"