feat: improve Discord API error messages (#289)

This commit is contained in:
David 2024-11-05 02:11:14 -05:00 committed by GitHub
parent ad71fc6805
commit 4f546b3ffc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -207,19 +207,33 @@ export class ApiHandler {
}); });
} }
parseError(method: HttpMethods, route: `/${string}`, response: Response, result: unknown) { parseError(method: HttpMethods, route: `/${string}`, response: Response, result: string | Record<string, any>) {
let errMessage = ''; let errMessage = '';
if (typeof result === 'object' && result) { if (typeof result === 'object') {
if ('message' in result) { errMessage += `${result.message ?? 'Unknown'} ${result.code ?? ''}\n[${response.status} ${response.statusText}] ${method} ${route}`;
errMessage += `${result.message}${'code' in result ? ` ${result.code}` : ''}\n`;
}
if ('errors' in result && result) { if ('errors' in result) {
errMessage += `${JSON.stringify(result.errors, null, 2)}\n`; const errors = this.parseValidationError(result.errors);
errMessage += `\n${errors.join('\n') || JSON.stringify(result.errors, null, 2)}`;
}
} else {
errMessage = `[${response.status} ${response.statusText}] ${method} ${route}`;
}
return new Error(errMessage);
}
parseValidationError(data: Record<string, any>, path = '', errors: string[] = []) {
for (const key in data) {
if (key === '_errors') {
for (const error of data[key]) {
errors.push(`${path.slice(0, -1)} [${error.code}]: ${error.message}`);
}
} else if (typeof data[key] === 'object') {
this.parseValidationError(data[key], `${path}${key}.`, errors);
} }
} }
errMessage += ` at [${response.status} ${response.statusText}] ${method} ${route}\n`;
return new Error(errMessage); return errors;
} }
async handle50X(method: HttpMethods, url: `/${string}`, request: ApiRequestOptions, next: () => void) { async handle50X(method: HttpMethods, url: `/${string}`, request: ApiRequestOptions, next: () => void) {