Skip to content

Commit

Permalink
improve error message when fail to get keys from torus.js
Browse files Browse the repository at this point in the history
  • Loading branch information
tanguyenvn committed Mar 13, 2024
1 parent 6749a2b commit 9fafb2a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import { registerServiceWorker } from "./registerServiceWorker";
import SentryHandler from "./sentry";
import { AGGREGATE_VERIFIER, LOGIN, SENTRY_TXNS, TORUS_METHOD, UX_MODE, UX_MODE_TYPE } from "./utils/enums";
import { serializeError } from "./utils/error";
import { handleRedirectParameters, isFirefox, padUrlString } from "./utils/helpers";
import log from "./utils/loglevel";
import StorageHelper from "./utils/StorageHelper";
Expand Down Expand Up @@ -496,9 +497,10 @@ class CustomAuth {
result = await this.triggerHybridAggregateLogin(methodArgs);
}
} catch (err: unknown) {
log.error(err);
const serializedError = await serializeError(err);
log.error(serializedError);
return {
error: `Could not get result from torus nodes \n ${(err as Error)?.message || ""}`,
error: `Could not get result from torus nodes. \n ${serializedError.message || ""}`,
state: instanceParameters || {},
method,
result: {},
Expand Down
26 changes: 26 additions & 0 deletions src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export const serializeError = async (error: unknown): Promise<Error> => {
// Find first Error or create an "unknown" Error to keep stack trace.
const isError = error instanceof Error;
const isString = typeof error === "string";
const isApiErrorIndex = error && typeof error === "object" && "status" in error && "type" in error;
let err: Error;
if (isApiErrorIndex) {
const apiError = error as Response;
const contentType = apiError.headers.get("content-type");
if (contentType.includes("application/json")) {
const errJson = await apiError.json();
err = new Error(errJson?.error || errJson?.message || JSON.stringify(errJson));
} else if (contentType.includes("text/plain")) {
err = new Error(await apiError.text());
} else {
err = new Error(`${apiError.status} ${apiError.type.toString()} ${apiError.statusText}`);
}
} else if (isString) {
err = new Error(error as string);
} else if (isError) {
err = error as Error;
} else {
err = new Error("Unknown error");
}
return err;
};

0 comments on commit 9fafb2a

Please sign in to comment.