Skip to content

Commit b924e0e

Browse files
Fix: Refactor error handling in project and folder creation to use a centralized function
1 parent 421d90f commit b924e0e

File tree

1 file changed

+25
-34
lines changed

1 file changed

+25
-34
lines changed

src/tools/testmanagement-utils/create-project-folder.ts

Lines changed: 25 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,29 @@ export const CreateProjFoldSchema = z.object({
3030

3131
type CreateProjFoldArgs = z.infer<typeof CreateProjFoldSchema>;
3232

33+
function formatAxiosError(
34+
err: unknown,
35+
defaultText: string,
36+
): { content: { type: "text"; text: string }[]; isError: true } {
37+
let text = defaultText;
38+
39+
if (err instanceof AxiosError && err.response?.data) {
40+
const { message: apiMessage } = err.response.data;
41+
const status = err.response.status;
42+
43+
if (status >= 400 && status < 500 && apiMessage) {
44+
text = apiMessage;
45+
}
46+
} else if (err instanceof Error) {
47+
text = err.message;
48+
}
49+
50+
return {
51+
content: [{ type: "text" as const, text }],
52+
isError: true,
53+
};
54+
}
55+
3356
/**
3457
* Creates a project and/or folder in BrowserStack Test Management.
3558
*/
@@ -77,23 +100,7 @@ export async function createProjectOrFolder(
77100

78101
projId = res.data.project.identifier;
79102
} catch (err) {
80-
let text = "Failed to create project.";
81-
82-
if (err instanceof AxiosError && err.response?.data) {
83-
const { error } = err.response.data;
84-
const status = err.response.status;
85-
86-
if (status >= 400 && status < 500 && error) {
87-
text = error;
88-
}
89-
} else if (err instanceof Error) {
90-
text = err.message;
91-
}
92-
93-
return {
94-
content: [{ type: "text", text }],
95-
isError: true,
96-
};
103+
return formatAxiosError(err, "Failed to create project..");
97104
}
98105
}
99106
// Step 2: Create folder if folder_name provided
@@ -136,23 +143,7 @@ export async function createProjectOrFolder(
136143
],
137144
};
138145
} catch (err) {
139-
let text = "Failed to create folder.";
140-
141-
if (err instanceof AxiosError && err.response?.data) {
142-
const { message: apiMessage } = err.response.data;
143-
const status = err.response.status;
144-
145-
if (status >= 400 && status < 500 && apiMessage) {
146-
text = apiMessage;
147-
}
148-
} else if (err instanceof Error) {
149-
text = err.message;
150-
}
151-
152-
return {
153-
content: [{ type: "text", text }],
154-
isError: true,
155-
};
146+
return formatAxiosError(err, "Failed to create folder.");
156147
}
157148
}
158149

0 commit comments

Comments
 (0)