Skip to content

Fix: Malformed error message formatting in makeMessage() function #1313

New issue

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

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

Already on GitHub? # to your account

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
26 changes: 20 additions & 6 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,37 @@ export class APIError<
readonly request_id: string | null | undefined;

constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {
super(`${APIError.makeMessage(status, error, message)}`);
// Always format message when constructing
const formattedMessage = APIError.makeMessage(status, error, message);
super(formattedMessage); // Use formatted message directly
this.status = status;
this.headers = headers;
this.request_id = headers?.['x-request-id'];
this.error = error;
this.error = formattedMessage;

const data = error as Record<string, any>;
this.code = data?.['code'];
this.param = data?.['param'];
this.type = data?.['type'];
}

// New helper function to format the error message
private static formatErrorMessage(error: any): string {
if (!error) return '';

if (typeof error.message === 'string') {
return error.message
.replace(/'/g, '"') // Convert single quotes to double quotes
.replace(/\(\s*([^()]+?)\s*\)/g, (_, content) => `[${content.split(/\s*,\s*/).join(', ')}]`);
// Convert tuples of any length to arrays
}

return JSON.stringify(error.message ?? error);
}

private static makeMessage(status: number | undefined, error: any, message: string | undefined) {
const msg =
error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
error?.message ? APIError.formatErrorMessage(error)
: error ? JSON.stringify(error)
: message;

Expand Down Expand Up @@ -100,6 +113,7 @@ export class APIError<
return new InternalServerError(status, error, message, headers);
}

// Default to a generic APIError if no specific handling
return new APIError(status, error, message, headers);
}
}
Expand Down