diff --git a/src/error.ts b/src/error.ts new file mode 100644 index 0000000..01c9a87 --- /dev/null +++ b/src/error.ts @@ -0,0 +1,13 @@ +class ResponseError extends Error { + constructor( + public error: string, + public status_code: number, + ) { + super(error) + this.name = 'ResponseError' + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ResponseError) + } + } +} diff --git a/src/utils.ts b/src/utils.ts index 0389f11..d0b3c0d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -15,11 +15,12 @@ export const formatAddress = (address: string): string => { const checkOk = async (response: Response): Promise => { if (!response.ok) { let message = `Error ${response.status}: ${response.statusText}` + let errorData: ErrorResponse | null = null if (response.headers.get('content-type')?.includes('application/json')) { try { - const errorResponse = (await response.json()) as ErrorResponse - message = errorResponse.error || message + errorData = (await response.json()) as ErrorResponse + message = errorData.error || message } catch (error) { console.log('Failed to parse error response as JSON') } @@ -33,7 +34,7 @@ const checkOk = async (response: Response): Promise => { } } - throw new Error(message) + throw new ResponseError(message, response.status) } }