Skip to content

Commit 4dd6842

Browse files
Merge pull request #310 from torusresearch/feat/improve-error-msg
improve error message when fail to get keys from torus.js
2 parents c5dae56 + 9fafb2a commit 4dd6842

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/login.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { registerServiceWorker } from "./registerServiceWorker";
2525
import SentryHandler from "./sentry";
2626
import { AGGREGATE_VERIFIER, LOGIN, SENTRY_TXNS, TORUS_METHOD, UX_MODE, UX_MODE_TYPE } from "./utils/enums";
27+
import { serializeError } from "./utils/error";
2728
import { handleRedirectParameters, isFirefox, padUrlString } from "./utils/helpers";
2829
import log from "./utils/loglevel";
2930
import StorageHelper from "./utils/StorageHelper";
@@ -496,9 +497,10 @@ class CustomAuth {
496497
result = await this.triggerHybridAggregateLogin(methodArgs);
497498
}
498499
} catch (err: unknown) {
499-
log.error(err);
500+
const serializedError = await serializeError(err);
501+
log.error(serializedError);
500502
return {
501-
error: `Could not get result from torus nodes \n ${(err as Error)?.message || ""}`,
503+
error: `Could not get result from torus nodes. \n ${serializedError.message || ""}`,
502504
state: instanceParameters || {},
503505
method,
504506
result: {},

src/utils/error.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export const serializeError = async (error: unknown): Promise<Error> => {
2+
// Find first Error or create an "unknown" Error to keep stack trace.
3+
const isError = error instanceof Error;
4+
const isString = typeof error === "string";
5+
const isApiErrorIndex = error && typeof error === "object" && "status" in error && "type" in error;
6+
let err: Error;
7+
if (isApiErrorIndex) {
8+
const apiError = error as Response;
9+
const contentType = apiError.headers.get("content-type");
10+
if (contentType.includes("application/json")) {
11+
const errJson = await apiError.json();
12+
err = new Error(errJson?.error || errJson?.message || JSON.stringify(errJson));
13+
} else if (contentType.includes("text/plain")) {
14+
err = new Error(await apiError.text());
15+
} else {
16+
err = new Error(`${apiError.status} ${apiError.type.toString()} ${apiError.statusText}`);
17+
}
18+
} else if (isString) {
19+
err = new Error(error as string);
20+
} else if (isError) {
21+
err = error as Error;
22+
} else {
23+
err = new Error("Unknown error");
24+
}
25+
return err;
26+
};

0 commit comments

Comments
 (0)