Skip to content

Commit 386894b

Browse files
committed
fix:refactor error handling logic
Signed-off-by: Amitkanswal <[email protected]>
1 parent 9976df2 commit 386894b

File tree

2 files changed

+64
-73
lines changed

2 files changed

+64
-73
lines changed

src/utils/adapter.ts

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,37 @@
11
import PostRobot from "post-robot";
2-
import { Response } from 'node-fetch';
3-
import { AxiosRequestConfig, AxiosResponse } from "axios";
2+
import { Response } from "node-fetch";
3+
import {
4+
AxiosError,
5+
AxiosRequestConfig,
6+
AxiosResponse,
7+
} from "axios";
48

5-
import { onError, fetchToAxiosConfig, serializeAxiosResponse, handleApiError, sanitizeResponseHeader } from "./utils";
9+
import {
10+
onError,
11+
fetchToAxiosConfig,
12+
handleApiError,
13+
sanitizeResponseHeader,
14+
} from "./utils";
615

716
/**
817
* Dispatches a request using PostRobot.
918
* @param postRobot - The PostRobot instance.
1019
* @returns A function that takes AxiosRequestConfig and returns a promise.
1120
*/
12-
export const dispatchAdapter = (postRobot: typeof PostRobot) => (config: AxiosRequestConfig): Promise<AxiosResponse> => {
13-
return postRobot
14-
.sendToParent("apiAdapter", config)
15-
.then((event:unknown) => {
16-
const { data } = event as { data: AxiosResponse };
17-
if (data.status >= 400) {
18-
throw serializeAxiosResponse(data, config);
19-
}
20-
return serializeAxiosResponse(data, config);
21-
})
22-
.catch(onError);
23-
};
21+
export const dispatchAdapter =
22+
(postRobot: typeof PostRobot) =>
23+
(config: AxiosRequestConfig): Promise<AxiosResponse> => {
24+
return postRobot
25+
.sendToParent("apiAdapter", config)
26+
.then((event: unknown) => {
27+
const { data } = event as { data: AxiosResponse };
28+
if (data.status >= 400) {
29+
throw data
30+
}
31+
return data as AxiosResponse;
32+
})
33+
.catch((err)=>onError(err));
34+
};
2435
/**
2536
* Dispatches an API request using axios and PostRobot.
2637
* @param url - The URL of the API endpoint.
@@ -29,22 +40,24 @@ export const dispatchAdapter = (postRobot: typeof PostRobot) => (config: AxiosRe
2940
*/
3041
export const dispatchApiRequest = async (
3142
url: string,
32-
options?: RequestInit,
43+
options?: RequestInit
3344
): Promise<Response> => {
3445
try {
3546
const config = fetchToAxiosConfig(url, options);
3647
const responseData = (await dispatchAdapter(PostRobot)(
3748
config
3849
)) as AxiosResponse;
50+
3951

4052
return new Response(responseData?.data, {
4153
status: responseData.status,
4254
statusText: responseData.statusText,
4355
url: responseData.config.url,
44-
headers: new Headers(sanitizeResponseHeader(responseData.config.headers || {})),
56+
headers: new Headers(
57+
sanitizeResponseHeader(responseData.config.headers || {})
58+
),
4559
});
46-
4760
} catch (error) {
48-
return handleApiError(error);
49-
}
61+
return handleApiError(error as AxiosResponse | AxiosError);
62+
}
5063
};

src/utils/utils.ts

Lines changed: 31 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ import { Response } from "node-fetch";
1010

1111
import { Region, RegionType } from "../types";
1212

13+
const filterHeaders = [
14+
"api_key",
15+
"authorization",
16+
"auth_token",
17+
"x-api-key",
18+
"user-agent",
19+
];
20+
1321
export function onData<Data extends Record<string, any>>(data: { data: Data }) {
1422
if (typeof data.data === "string") {
1523
return Promise.reject(data.data);
@@ -21,58 +29,38 @@ export function onError(error: Error) {
2129
return Promise.reject(error);
2230
}
2331

24-
export const createAxiosErrorResponse = (error: AxiosError): Response => {
25-
const { response, message, config } = error;
32+
export function sanitizeResponseHeader(axiosHeaders) {
33+
const fetchHeaders = new Headers();
34+
for (const key in axiosHeaders) {
35+
if (axiosHeaders.hasOwnProperty(key) && !filterHeaders.includes(key)) {
36+
fetchHeaders.append(key, axiosHeaders[key]);
37+
}
38+
}
39+
return fetchHeaders;
40+
};
41+
export const handleApiError = (error: AxiosResponse | AxiosError): Response => {
42+
// Extract relevant information from the error
43+
const isServerError = (error as AxiosResponse).status >= 500;
44+
const responseBody = isServerError
45+
? (error as AxiosError).stack || "Internal Server Error"
46+
: (error as AxiosResponse).data || "An error occurred";
47+
48+
const status = (error as AxiosResponse).status || 500;
49+
const statusText =
50+
isServerError
51+
? (error as AxiosError).message || "Internal Server Error"
52+
: (error as AxiosResponse).statusText || "Error";
2653

27-
const responseBody = response?.data || { message };
28-
const status = response?.status || 500;
29-
const statusText = response?.statusText || "Internal Server Error";
3054
const headers = new Headers(
31-
sanitizeResponseHeader(config?.headers || {})
55+
sanitizeResponseHeader((error as AxiosResponse).headers || {})
3256
);
3357

3458
return new Response(JSON.stringify(responseBody), {
3559
status,
3660
statusText,
3761
headers,
3862
});
39-
};
40-
41-
export const sanitizeResponseHeader = (headers: RawAxiosRequestHeaders) => {
42-
const responseHeaders = new Headers();
43-
const filterHeaders = [
44-
"api_key",
45-
"authorization",
46-
"x-api-key",
47-
"user-agent",
48-
];
49-
if (headers instanceof Headers) {
50-
headers.forEach((value, key) => {
51-
if (!filterHeaders.includes(key.toLowerCase())) {
52-
responseHeaders.set(key, value);
53-
}
54-
});
55-
}
56-
return responseHeaders;
57-
};
58-
59-
export const handleApiError = (error: unknown): Response => {
60-
return isAxiosError(error)
61-
? createErrorResponse(createAxiosErrorResponse(error))
62-
: createErrorResponse(error as Error);
63-
};
64-
65-
export const createErrorResponse = (error: Error): Response => {
66-
return new Response(
67-
JSON.stringify({ message: (error).message || error }),
68-
{
69-
status: 500,
70-
statusText: "Internal Server Error",
71-
headers: new Headers(),
72-
}
73-
);
74-
};
75-
63+
}
7664
export function formatAppRegion(region: string): RegionType {
7765
return region ?? Region.UNKNOWN;
7866
}
@@ -145,13 +133,3 @@ export const fetchToAxiosConfig = (
145133

146134
return axiosConfig;
147135
};
148-
149-
export const serializeAxiosResponse = (responseData: AxiosResponse, config) => {
150-
return {
151-
data: responseData.data,
152-
status: responseData.status,
153-
statusText: responseData.statusText,
154-
headers: responseData.headers as AxiosHeaders,
155-
config,
156-
};
157-
};

0 commit comments

Comments
 (0)