From d8869048881df44a8829a8c996455f5e03a10f29 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 29 May 2023 22:28:26 -0400 Subject: [PATCH] Better error wrapping. (#126) * Better error wrapping. * Simplifying * Moving return to else. --- package.json | 13 +++---------- src/http.ts | 22 +++++++--------------- 2 files changed, 10 insertions(+), 25 deletions(-) diff --git a/package.json b/package.json index aa17dee..bb05eaa 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,7 @@ "author": "Dessalines ", "main": "./dist/index.js", "types": "./dist/index.d.ts", - "files": [ - "/dist" - ], + "files": ["/dist"], "scripts": { "build": "tsc", "docs": "typedoc src/index.ts", @@ -17,13 +15,8 @@ "prepare": "yarn run build && husky install" }, "lint-staged": { - "*.{ts,tsx,js}": [ - "prettier --write", - "eslint --fix" - ], - "package.json": [ - "sortpack" - ] + "*.{ts,tsx,js}": ["prettier --write", "eslint --fix"], + "package.json": ["sortpack"] }, "dependencies": { "cross-fetch": "^3.1.5", diff --git a/src/http.ts b/src/http.ts index 7130ce0..57f739f 100644 --- a/src/http.ts +++ b/src/http.ts @@ -1295,18 +1295,15 @@ export class LemmyHttp { endpoint: string, form: BodyType ): Promise { + let response: Response; if (type_ === HttpType.Get) { const getUrl = `${this.buildFullUrl(endpoint)}?${encodeGetParams(form)}`; - const response = await fetch(getUrl, { + response = await fetch(getUrl, { method: HttpType.Get, headers: this.headers, }); - - await this.checkandThrowError(response); - - return await response.json(); } else { - const response = await fetch(this.buildFullUrl(endpoint), { + response = await fetch(this.buildFullUrl(endpoint), { method: type_, headers: { "Content-Type": "application/json", @@ -1314,18 +1311,13 @@ export class LemmyHttp { }, body: JSON.stringify(form), }); - - await this.checkandThrowError(response); - - return await response.json(); } - } + const json = await response.json(); - private async checkandThrowError(response: Response) { if (!response.ok) { - const errJson = await response.json(); - const errString: string = errJson["error"] ?? response.statusText; - throw new Error(errString); + throw json["error"] ?? response.statusText; + } else { + return json; } } }