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 82796eb
Showing 1 changed file with 44 additions and 10 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;
}
}

0 comments on commit 82796eb

Please sign in to comment.