Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/react/src/definitions/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,14 @@ export interface ApiError {
statusCode: number;
message: string;
}

export class ApiException extends Error implements ApiError {
constructor(
public readonly statusCode: number,
message: string,
) {
super(message);
this.name = 'ApiException';
Object.setPrototypeOf(this, ApiException.prototype);
}
}
18 changes: 10 additions & 8 deletions packages/react/src/hooks/api.hook.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useMemo } from 'react';
import { useAuthContext } from '../contexts/auth.context';
import { ApiError } from '../definitions/error';
import { ApiError, ApiException } from '../definitions/error';

export interface ApiInterface {
defaultUrl: string;
Expand Down Expand Up @@ -46,10 +46,7 @@ export function useApi(): ApiInterface {
)
.catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
throw {
statusCode: 0,
message: `Network error: ${message}`,
} as ApiError;
throw new ApiException(0, `Network error: ${message}`);
})
.then((response) => {
if (response.status === config.specialHandling?.statusCode) {
Expand All @@ -71,9 +68,14 @@ export function useApi(): ApiInterface {
}
}

return response.json().then((body) => {
throw body;
});
return response.json()
.catch(() => null)
.then((body: Partial<ApiError> | null) => {
throw new ApiException(
body?.statusCode ?? response.status,
body?.message ?? response.statusText ?? 'Unknown error',
);
});
});
}, [url, defaultVersion]);

Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export { Bank } from './definitions/bank';
export { Blockchain } from './definitions/blockchain';
export { Buy, BuyPaymentInfo, PdfDocument } from './definitions/buy';
export { Country } from './definitions/country';
export { ApiError } from './definitions/error';
export { ApiError, ApiException } from './definitions/error';
export { Fiat } from './definitions/fiat';
export { CustomFile } from './definitions/file';
export {
Expand Down