Skip to content

Commit

Permalink
include response in errors thrown by requests
Browse files Browse the repository at this point in the history
  • Loading branch information
angusfretwell committed Sep 21, 2024
1 parent 6dbeb4d commit bd7ba1b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 12 deletions.
54 changes: 44 additions & 10 deletions src/lib/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,6 @@ function authenticationHeader(auth?: Authentication): string {
throw new Error("auth must contain apiKey, jwt, or username/password");
}

function handleError(error: string) {
if (this.debug) {
console.error(error);
console.groupEnd();
}

// TODO: make this error more informative
throw new Error("CiviCRM request failed");
}

export function bindRequest(
requestFn: BaseRequestFn<any, any>,
config: ClientConfig<any, any>,
Expand Down Expand Up @@ -102,3 +92,47 @@ export async function request(

return json.values;
}

function handleError(errorResponse: string | object) {
const error = new CiviCRMRequestError(errorResponse);

if (this.debug) {
console.error(error);
console.groupEnd();
}

throw error;
}

class CiviCRMRequestError extends Error {
name = "CiviCRMRequestError";
message: string;
detail: any;

parseError(error: string | { error_message: string }) {
if (typeof error === "object") {
return error;
}

try {
const object = JSON.parse(error);

if (object && typeof object === "object") {
return object;
}
} catch (e) {}

return {
error_message: error || "CiviCRM request failed",
};
}

constructor(error: any) {
super();

const { error_message, ...detail } = this.parseError(error);

this.message = error_message;
this.detail = detail;
}
}
7 changes: 6 additions & 1 deletion test/api3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,12 @@ describe("debug", () => {
} catch {}

expect(consoleSpy.group).toHaveBeenCalled();
expect(consoleSpy.error).toHaveBeenCalledWith("Internal Server Error");
expect(consoleSpy.error).toHaveBeenCalledWith(
expect.objectContaining({
name: "CiviCRMRequestError",
message: "Internal Server Error",
}),
);
expect(consoleSpy.groupEnd).toHaveBeenCalled();
});
});
7 changes: 6 additions & 1 deletion test/api4.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ describe("debug", () => {
} catch {}

expect(consoleSpy.group).toHaveBeenCalled();
expect(consoleSpy.error).toHaveBeenCalledWith("Internal Server Error");
expect(consoleSpy.error).toHaveBeenCalledWith(
expect.objectContaining({
name: "CiviCRMRequestError",
message: "Internal Server Error",
}),
);
expect(consoleSpy.groupEnd).toHaveBeenCalled();
});
});

0 comments on commit bd7ba1b

Please sign in to comment.