Merge pull request #122 from LemmyNet/add_error_message_as_exception

Making the http `{"error": "..."}` json into a string exception.
This commit is contained in:
SleeplessOne1917 2023-05-24 00:45:01 +00:00 committed by GitHub
commit a6278881ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1282,6 +1282,8 @@ export class LemmyHttp {
headers: this.headers, headers: this.headers,
}); });
await this.checkandThrowError(response);
return await response.json(); return await response.json();
} else { } else {
const response = await fetch(this.buildFullUrl(endpoint), { const response = await fetch(this.buildFullUrl(endpoint), {
@ -1293,9 +1295,19 @@ export class LemmyHttp {
body: JSON.stringify(form), body: JSON.stringify(form),
}); });
await this.checkandThrowError(response);
return await response.json(); return 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);
}
}
} }
function encodeGetParams<BodyType extends object>(p: BodyType): string { function encodeGetParams<BodyType extends object>(p: BodyType): string {