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:
commit
1415d1f2eb
2 changed files with 12 additions and 22 deletions
|
@ -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);
|
||||||
const {
|
} else if (jsonBody) {
|
||||||
errors: [message]
|
const {
|
||||||
} = await response.clone().json();
|
errors: [message]
|
||||||
reject(message);
|
} = jsonBody as { errors: string[] };
|
||||||
} catch {
|
reject(message);
|
||||||
reject(await response.text());
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
reject(message);
|
reject(message);
|
||||||
}
|
}
|
||||||
|
|
|
@ -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);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue