Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch error handing revisited #8081

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { decryptRSAWithJWK, encryptRSAWithJWK } from '../../../../account/crypt'
import { getCurrentSessionId, getPrivateKey } from '../../../../account/session';
import { SegmentEvent } from '../../../analytics';
import useStateRef from '../../../hooks/use-state-ref';
import { insomniaFetch, ResponseFailError } from '../../../insomniaFetch';
import { insomniaFetch } from '../../../insomniaFetch';
import { Icon } from '../../icon';
import { type PendingMember, updateInvitationRole } from './invite-modal';
import { OrganizationMemberRolesSelector, type Role, SELECTOR_TYPE } from './organization-member-roles-selector';
Expand Down Expand Up @@ -240,25 +240,19 @@ async function getInviteInstruction(
sessionId: await getCurrentSessionId(),
onlyResolveOnSuccess: true,
}).catch(async error => {
if (error instanceof ResponseFailError && error.response.headers.get('content-type')?.includes('application/json')) {
let json;
try {
json = await error.response.json();
} catch (e) {
throw new Error(`Failed to get invite instruction for ${inviteeEmail}`);
}
if (json?.error === NEEDS_TO_UPGRADE_ERROR) {
if (error.message && error.error) {
if (error?.error === NEEDS_TO_UPGRADE_ERROR) {
throw new Error(
`You are currently on the Free plan where you can invite as many collaborators as you want only as long as
you don’t have more than one project. Since you have more than one project, you need to upgrade to
Individual or above to continue.`
);
}
if (json?.error === NEEDS_TO_INCREASE_SEATS_ERROR) {
if (error?.error === NEEDS_TO_INCREASE_SEATS_ERROR) {
throw new Error(needToIncreaseSeatErrMsg);
}
if (json?.message) {
throw new Error(json.message);
if (error?.message) {
throw new Error(error.message);
}
}
throw new Error(`Failed to get invite instruction for ${inviteeEmail}`);
Expand Down Expand Up @@ -455,11 +449,7 @@ async function inviteUserToOrganization(
}).then(
() => inviteeEmail,
async error => {
let errMsg = `Failed to invite ${inviteeEmail}`;
if (error instanceof ResponseFailError && error.message) {
errMsg = error.message;
}
throw new Error(errMsg);
throw new Error(error.message || `Failed to invite ${inviteeEmail}`);
}
);
}
Expand Down
46 changes: 18 additions & 28 deletions packages/insomnia/src/ui/insomniaFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,8 @@ interface FetchConfig {
retries?: number;
origin?: string;
headers?: Record<string, string>;
onlyResolveOnSuccess?: boolean;
timeout?: number;
}

export class ResponseFailError extends Error {
constructor(msg: string, response: Response) {
super(msg);
this.response = response;
}
response;
name = 'ResponseFailError';
onlyResolveOnSuccess?: boolean;
}

// Adds headers, retries and opens deep links returned from the api
Expand All @@ -33,8 +24,8 @@ export async function insomniaFetch<T = void>({
organizationId,
origin,
headers,
onlyResolveOnSuccess = false,
timeout = INSOMNIA_FETCH_TIME_OUT,
timeout,
onlyResolveOnSuccess,
}: FetchConfig): Promise<T> {
const config: RequestInit = {
method,
Expand All @@ -49,7 +40,7 @@ export async function insomniaFetch<T = void>({
...(PLAYWRIGHT ? { 'X-Mockbin-Test': 'true' } : {}),
},
...(data ? { body: JSON.stringify(data) } : {}),
signal: AbortSignal.timeout(timeout),
signal: AbortSignal.timeout(timeout || INSOMNIA_FETCH_TIME_OUT),
};
if (sessionId === undefined) {
throw new Error(`No session ID provided to ${method}:${path}`);
Expand All @@ -61,27 +52,26 @@ export async function insomniaFetch<T = void>({
if (uri) {
window.main.openDeepLink(uri);
}
const isJson =
response.headers.get('content-type')?.includes('application/json') ||
path.match(/\.json$/);
if (onlyResolveOnSuccess && !response.ok) {
let errMsg = '';
if (isJson) {
try {
const json = await response.json();
if (typeof json?.message === 'string') {
errMsg = json.message;
}
} catch (err) {}
const contentType = response.headers.get('content-type');
const isJson = contentType?.includes('application/json') || path.match(/\.json$/);

// assume the backend is sending us a meaningful error message
if (isJson && !response.ok && onlyResolveOnSuccess) {
try {
const json = await response.json();
throw ({
message: json?.message || '',
error: json?.error || '',
});
} catch (err) {
throw err;
}
throw new ResponseFailError(errMsg, response);
}
return isJson ? response.json() : response.text();
} catch (err) {
if (err.name === 'AbortError') {
throw new Error('insomniaFetch timed out');
} else {
throw err;
}
throw err;
}
}
Loading