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

View file

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