Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update backend error #1089

Merged
merged 3 commits into from
Dec 26, 2024
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
2 changes: 0 additions & 2 deletions js/src/sdk/base.toolset.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@

it("should have schema processor", async () => {
const addSchemaProcessor: TSchemaProcessor = ({
actionName,

Check warning on line 42 in js/src/sdk/base.toolset.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'actionName' is defined but never used. Allowed unused args must match /^_/u

Check warning on line 42 in js/src/sdk/base.toolset.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'actionName' is defined but never used. Allowed unused args must match /^_/u
toolSchema,
}) => {
console.log("actionName", actionName);
return {
...toolSchema,
parameters: {
Expand All @@ -53,10 +52,9 @@
};

toolset.addSchemaProcessor(addSchemaProcessor);
const tools = await toolset.getToolsSchema({

Check warning on line 55 in js/src/sdk/base.toolset.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'tools' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 55 in js/src/sdk/base.toolset.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'tools' is assigned a value but never used. Allowed unused vars must match /^_/u
actions: ["github_issues_create"],
});
console.log("tools", tools);
});

it("should execute an action", async () => {
Expand Down
70 changes: 48 additions & 22 deletions js/src/sdk/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,54 +26,66 @@
});

it("should handle 404 error gracefully", async () => {
const client = new Composio({ apiKey: COMPOSIO_API_KEY });
const mock = new AxiosMockAdapter(axiosClient.instance);
mock.onGet("/api/v1/apps").reply(404, { detail: "Not found" });
const mockError = {
error: {
type: "NotFoundError",
name: "AppNotFoundError",
message: "Not found",
},
};
mock.onGet("/api/v1/apps").reply(404, mockError);

const client = new Composio({ apiKey: COMPOSIO_API_KEY });

try {
await client.apps.list();
const apps = await client.apps.list();

Check warning on line 42 in js/src/sdk/index.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'apps' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 42 in js/src/sdk/index.spec.ts

View workflow job for this annotation

GitHub Actions / lint-and-prettify

'apps' is assigned a value but never used. Allowed unused vars must match /^_/u
} catch (e) {
const error = e as ComposioError;
const errorCode = COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND;
const errorInfo = BASE_ERROR_CODE_INFO[errorCode];
expect(error.errCode).toBe(errorCode);
expect(error.message).toContain(errorInfo.message);
expect(error.description).toBe(errorInfo.description);
expect(error.errorId).toBeDefined();
expect(error.name).toBe("ComposioError");
expect(error.possibleFix).toBe(errorInfo.possibleFix);
if (e instanceof ComposioError) {
expect(e.errCode).toBe(COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND);
expect(e.description).toBe("Not found");
expect(e.errorId).toBeDefined();
expect(e.name).toBe("ComposioError");
expect(e.possibleFix).toBe(e.possibleFix);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test assertion expect(e.possibleFix).toBe(e.possibleFix) is comparing a value with itself, which will always pass. This should probably be comparing against an expected value instead.

expect(e.message).toContain(mockError.error.message);
expect(e.message).toContain(mockError.error.name);
} else {
throw e;
}
}

mock.reset();
});

it("should handle 400 error gracefully", async () => {
const client = new Composio({ apiKey: COMPOSIO_API_KEY });
const mock = new AxiosMockAdapter(axiosClient.instance);
mock
.onGet("/api/v1/apps")
.reply(400, { errors: ["Invalid request for apps"] });
mock.onGet("/api/v1/apps").reply(400, {
error: {
type: "BadRequestError",
name: "InvalidRequestError",
message: "Invalid request for apps",
},
});

const client = new Composio({ apiKey: COMPOSIO_API_KEY });
try {
await client.apps.list();
} catch (e) {
const error = e as ComposioError;
const errorCode = COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST;
expect(error.errCode).toBe(errorCode);
expect(error.message).toContain(
"Validation Errors while making request to https://backend.composio.dev/api/v1/apps"
);
expect(error.message).toContain("InvalidRequestError ");
expect(error.message).toContain("InvalidRequestError");
expect(error.description).toContain("Invalid request for apps");
}

mock.reset();
});

it("should handle 500 and 502 error gracefully", async () => {
const client = new Composio({ apiKey: COMPOSIO_API_KEY });
it("should handle 500 and 502 error gracefully, and without backend fix", async () => {
const mock = new AxiosMockAdapter(axiosClient.instance);
mock.onGet("/api/v1/apps").reply(500, { detail: "Internal Server Error" });

const client = new Composio({ apiKey: COMPOSIO_API_KEY });
try {
await client.apps.list();
} catch (e) {
Expand Down Expand Up @@ -105,6 +117,20 @@
}

mock.reset();

mock.onGet("/api/v1/apps").reply(500, {
error: {
type: "NotFoundError",
name: "AppNotFoundError",
message: "Not found",
},
});
try {
await client.apps.list();
} catch (e) {
const error = e as ComposioError;
expect(error.message).toContain("AppNotFoundError - NotFoundError");
}
});

it("should give request timeout error", async () => {
Expand Down
2 changes: 2 additions & 0 deletions js/src/sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
ZGetExpectedParamsForUserParams,
ZGetExpectedParamsRes,
} from "../types/composio";
import { getUUID } from "../utils/common";
import { ZAuthMode } from "./types/integration";

export type ComposioInputFieldsParams = z.infer<
Expand Down Expand Up @@ -63,6 +64,7 @@ export class Composio {
);

ComposioSDKContext.apiKey = apiKeyParsed;
ComposioSDKContext.sessionId = getUUID();
ComposioSDKContext.baseURL = baseURLParsed;
ComposioSDKContext.frameworkRuntime = config?.runtime;

Expand Down
4 changes: 4 additions & 0 deletions js/src/sdk/models/backendClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AxiosInstance } from "axios";
import apiClient from "../client/client";
import { client as axiosClient } from "../client/services.gen";
import { setAxiosClientConfig } from "../utils/config";
Expand All @@ -22,6 +23,7 @@ export class BackendClient {
* The runtime environment where the client is being used.
*/
public runtime: string;
public instance: AxiosInstance;

/**
* Creates an instance of apiClientDetails.
Expand All @@ -34,6 +36,7 @@ export class BackendClient {
this.runtime = runtime || "";
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.instance = axiosClient.instance;

if (!apiKey) {
throw CEG.getCustomError(
Expand Down Expand Up @@ -86,5 +89,6 @@ export class BackendClient {
});

setAxiosClientConfig(axiosClient.instance);
this.instance = axiosClient.instance;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant assignment of this.instance. This is already assigned on line 39. Consider removing this duplicate assignment or add a comment explaining why it's needed twice.

}
}
1 change: 1 addition & 0 deletions js/src/sdk/utils/composioContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class ComposioSDKContext {
static frameworkRuntime?: string;
static source?: string = "javascript";
static composioVersion?: string;
static sessionId?: string;
}

export default ComposioSDKContext;
9 changes: 3 additions & 6 deletions js/src/sdk/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { AxiosError } from "axios";
import { ZodError } from "zod";
import { ComposioError } from "./errors/src/composioError";
import {
API_TO_SDK_ERROR_CODE,
BASE_ERROR_CODE_INFO,
BE_STATUS_CODE_TO_SDK_ERROR_CODES,
COMPOSIO_SDK_ERROR_CODES,
} from "./errors/src/constants";
import {
Expand Down Expand Up @@ -124,15 +124,12 @@ export class CEG {
static throwAPIError(error: AxiosError) {
const statusCode = error?.response?.status || null;
const errorCode = statusCode
? BE_STATUS_CODE_TO_SDK_ERROR_CODES[statusCode] ||
? API_TO_SDK_ERROR_CODE[statusCode] ||
COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN
: COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN;
const predefinedError = BASE_ERROR_CODE_INFO[errorCode];

const errorDetails = getAPIErrorDetails(
errorCode,
error as AxiosError<ErrorResponseData>,
predefinedError
error as AxiosError<ErrorResponseData>
);

const metadata = generateMetadataFromAxiosError(error);
Expand Down
2 changes: 1 addition & 1 deletion js/src/sdk/utils/errors/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const BASE_ERROR_CODE_INFO = {
},
};

export const BE_STATUS_CODE_TO_SDK_ERROR_CODES = {
export const API_TO_SDK_ERROR_CODE = {
400: COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST,
401: COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED,
404: COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND,
Expand Down
82 changes: 36 additions & 46 deletions js/src/sdk/utils/errors/src/formatter.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { AxiosError } from "axios";
import { COMPOSIO_SDK_ERROR_CODES } from "./constants";
import {
API_TO_SDK_ERROR_CODE,
BASE_ERROR_CODE_INFO,
COMPOSIO_SDK_ERROR_CODES,
} from "./constants";

export interface ErrorResponseData {
message: string;
error: string;
errors?: Record<string, unknown>[];
error: {
type: string;
name: string;
message: string;
};
}

interface ErrorDetails {
Expand All @@ -15,72 +21,56 @@ interface ErrorDetails {
}

export const getAPIErrorDetails = (
errorKey: string,
axiosError: AxiosError<ErrorResponseData>,
predefinedError: Record<string, unknown>
axiosError: AxiosError<ErrorResponseData>
): ErrorDetails => {
const statusCode = axiosError.response?.status;
const errorCode = statusCode
? API_TO_SDK_ERROR_CODE[statusCode]
: COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN;
const predefinedError = BASE_ERROR_CODE_INFO[errorCode];

const defaultErrorDetails = {
message: axiosError.message,
description:
axiosError.response?.data?.message ||
axiosError.response?.data?.error?.message ||
axiosError.response?.data?.error ||
axiosError.message,
possibleFix:
"Please check the network connection, request parameters, and ensure the API endpoint is correct.",
};

const metadata = generateMetadataFromAxiosError(axiosError);
switch (errorKey) {

const errorNameFromBE = axiosError.response?.data?.error?.name;
const errorTypeFromBE = axiosError.response?.data?.error?.type;
const errorMessage = axiosError.response?.data?.error?.message;

const genericMessage = `${errorNameFromBE || predefinedError.message} ${errorTypeFromBE ? `- ${errorTypeFromBE}` : ""} on ${axiosError.config?.baseURL! + axiosError.config?.url!}`;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding null/undefined checks for axiosError.config?.baseURL and axiosError.config?.url. While the optional chaining helps prevent crashes, concatenating with undefined values could lead to "undefined" appearing in the error message.


switch (errorCode) {
case COMPOSIO_SDK_ERROR_CODES.BACKEND.NOT_FOUND:
case COMPOSIO_SDK_ERROR_CODES.BACKEND.UNAUTHORIZED:
case COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_ERROR:
case COMPOSIO_SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE:
case COMPOSIO_SDK_ERROR_CODES.BACKEND.RATE_LIMIT:
return {
message: `${predefinedError.message || axiosError.message} for ${axiosError.config?.baseURL! + axiosError.config?.url!}`,
description: (axiosError.response?.data?.message! ||
predefinedError.description) as string,
possibleFix: (predefinedError.possibleFix! ||
defaultErrorDetails.possibleFix) as string,
metadata,
};

case COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN:
case COMPOSIO_SDK_ERROR_CODES.BACKEND.BAD_REQUEST:
const validationErrors = axiosError.response?.data?.errors;
const formattedErrors = Array.isArray(validationErrors)
? validationErrors
.map((err) => JSON.stringify(err as Record<string, unknown>))
.join(", ")
: JSON.stringify(
validationErrors as unknown as Record<string, unknown>
);

return {
message: `Validation Errors while making request to ${axiosError.config?.baseURL! + axiosError.config?.url!}`,
description: `Validation Errors: ${formattedErrors}`,
message: genericMessage,
description: errorMessage || (predefinedError.description as string),
possibleFix:
"Please check the request parameters and ensure they are correct.",
metadata,
};

case COMPOSIO_SDK_ERROR_CODES.BACKEND.UNKNOWN:
case COMPOSIO_SDK_ERROR_CODES.COMMON.UNKNOWN:
return {
message: `${axiosError.message} for ${axiosError.config?.baseURL! + axiosError.config?.url!}`,
description: (axiosError.response?.data?.message! ||
axiosError.response?.data?.error! ||
axiosError.message) as string,
possibleFix: "Please contact tech@composio.dev with the error details.",
predefinedError.possibleFix! ||
(defaultErrorDetails.possibleFix as string),
metadata,
};

default:
return {
message: `${predefinedError.message || axiosError.message} for ${axiosError.config?.baseURL! + axiosError.config?.url!}`,
description: (axiosError.response?.data?.message! ||
predefinedError.description) as string,
possibleFix: (predefinedError.possibleFix! ||
defaultErrorDetails.possibleFix) as string,
message: genericMessage,
description: errorMessage || (predefinedError.description as string),
possibleFix:
predefinedError.possibleFix! ||
(defaultErrorDetails.possibleFix as string),
metadata,
};
}
Expand Down
Loading