-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improve error message when fail to get keys from torus.js
- Loading branch information
1 parent
6749a2b
commit 9fafb2a
Showing
2 changed files
with
30 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |