mirror of
https://github.com/logto-io/logto.git
synced 2025-03-10 22:22:45 -05:00
fix(console): avoid reading response error body more than once (#4223)
This commit is contained in:
parent
6bef85fdb1
commit
9d02e1300c
2 changed files with 18 additions and 13 deletions
|
@ -1,6 +1,6 @@
|
|||
import type router from '@logto/cloud/routes';
|
||||
import { useLogto } from '@logto/react';
|
||||
import { conditional } from '@silverhand/essentials';
|
||||
import { conditional, trySafe } from '@silverhand/essentials';
|
||||
import Client, { ResponseError } from '@withtyped/client';
|
||||
import { useMemo } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
@ -8,15 +8,24 @@ import { z } from 'zod';
|
|||
|
||||
import { cloudApi } from '@/consts';
|
||||
|
||||
export const responseErrorBodyGuard = z.object({
|
||||
const responseErrorBodyGuard = z.object({
|
||||
message: z.string(),
|
||||
});
|
||||
|
||||
export const tryReadResponseErrorBody = async (error: ResponseError) =>
|
||||
trySafe(async () => {
|
||||
// Clone the response to avoid blocking later usage since the response body can only be read once
|
||||
const responseBody = await error.response.clone().json();
|
||||
return responseErrorBodyGuard.parse(responseBody);
|
||||
});
|
||||
|
||||
export const toastResponseError = async (error: unknown) => {
|
||||
if (error instanceof ResponseError) {
|
||||
const parsed = responseErrorBodyGuard.safeParse(await error.response.json());
|
||||
toast.error(parsed.success ? parsed.data.message : error.message);
|
||||
return;
|
||||
const responseBody = await tryReadResponseErrorBody(error);
|
||||
if (responseBody) {
|
||||
toast.error(responseBody.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
toast(error instanceof Error ? error.message : String(error));
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import { ResponseError } from '@withtyped/client';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import { responseErrorBodyGuard } from '@/cloud/hooks/use-cloud-api';
|
||||
import { tryReadResponseErrorBody } from '@/cloud/hooks/use-cloud-api';
|
||||
import { type SubscriptionPlanResponse } from '@/cloud/types/router';
|
||||
import {
|
||||
communitySupportEnabledMap,
|
||||
|
@ -64,11 +64,7 @@ export const isExceededQuotaLimitError = async (error: unknown) => {
|
|||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const responseBody = await error.response.json();
|
||||
const { message } = responseErrorBodyGuard.parse(responseBody);
|
||||
return message.includes('Exceeded quota limit');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const { message } = (await tryReadResponseErrorBody(error)) ?? {};
|
||||
|
||||
return Boolean(message?.includes('Exceeded quota limit'));
|
||||
};
|
||||
|
|
Loading…
Add table
Reference in a new issue