From 4f546b3ffce0a4b75ba0e00db8a8548d4cb099ff Mon Sep 17 00:00:00 2001 From: David <35281350+Drylozu@users.noreply.github.com> Date: Tue, 5 Nov 2024 02:11:14 -0500 Subject: [PATCH] feat: improve Discord API error messages (#289) --- src/api/api.ts | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/api/api.ts b/src/api/api.ts index 56a037e..de88f4a 100644 --- a/src/api/api.ts +++ b/src/api/api.ts @@ -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) { let errMessage = ''; - if (typeof result === 'object' && result) { - if ('message' in result) { - errMessage += `${result.message}${'code' in result ? ` ${result.code}` : ''}\n`; - } + if (typeof result === 'object') { + errMessage += `${result.message ?? 'Unknown'} ${result.code ?? ''}\n[${response.status} ${response.statusText}] ${method} ${route}`; - if ('errors' in result && result) { - errMessage += `${JSON.stringify(result.errors, null, 2)}\n`; + if ('errors' in result) { + 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, 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) {