Merge pull request #7319 from tchak/fix-parse-error-body-on-fetch

fix(fetch): prevent double parsing of fetch error messages
This commit is contained in:
Paul Chavard 2022-05-17 10:42:06 +02:00 committed by GitHub
commit 1415d1f2eb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 22 deletions

View file

@ -1,4 +1,4 @@
import { httpRequest } from '@utils';
import { httpRequest, ResponseError } from '@utils';
import invariant from 'tiny-invariant';
type Operation = {
@ -48,28 +48,22 @@ export class OperationsQueue {
const data = await httpRequest(url, { method, json: payload }).json();
resolve(data);
} catch (e) {
handleError(e as OperationError, reject);
handleError(e as ResponseError, reject);
}
}
}
class OperationError extends Error {
response?: Response;
}
async function handleError(
{ response, message }: OperationError,
{ message, textBody, jsonBody }: ResponseError,
reject: (error: string) => void
) {
if (response) {
try {
const {
errors: [message]
} = await response.clone().json();
reject(message);
} catch {
reject(await response.text());
}
if (textBody) {
reject(textBody);
} else if (jsonBody) {
const {
errors: [message]
} = jsonBody as { errors: string[] };
reject(message);
} else {
reject(message);
}

View file

@ -150,18 +150,14 @@ export function httpRequest(
let textBody: string | undefined;
try {
if (contentType?.match('json')) {
jsonBody = await response.json();
jsonBody = await response.clone().json();
} else {
textBody = await response.text();
textBody = await response.clone().text();
}
} catch {
// ignore
}
throw new ResponseError(response, jsonBody, textBody);
} catch (error) {
clearTimeout(timer);
throw error;
} finally {
clearTimeout(timer);
}