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';
|
||||
|
||||
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 {
|
||||
if (textBody) {
|
||||
reject(textBody);
|
||||
} else if (jsonBody) {
|
||||
const {
|
||||
errors: [message]
|
||||
} = await response.clone().json();
|
||||
} = jsonBody as { errors: string[] };
|
||||
reject(message);
|
||||
} catch {
|
||||
reject(await response.text());
|
||||
}
|
||||
} else {
|
||||
reject(message);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue