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

RED-33: Add error codes to places where we display error toasts/etc to the user #7

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from
Open
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
71 changes: 49 additions & 22 deletions hooks/fetcher.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,55 @@
import { authService } from '../services/auth.service'
import { useGlobals } from '../utils/globals'
import { isDev } from '../utils/is-dev'

const { apiBase } = useGlobals()

export const fetcher = <T>(input: RequestInfo | URL,
init: RequestInit,
showToast: (msg: string) => void): Promise<T> => {
return fetch(input, {
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Send cookies
...(init ?? {}),
}).then(async (res) => {
const data = await res.json();
if (res.status === 403) {
authService.logout(apiBase);
} else if (res.status === 500) {
showToast('<span>Sorry, something went wrong. Please report this issue to our support team so we can investigate and resolve the problem.</span>');
return;
} else if (!res.ok) {
console.log(data.errorDetails);
throw data.errorMessage;
function showErrorToast(showToast: (msg: string) => void, status: number, resource: string): void {
const message = `Error (${status}): Failed to fetch ${resource}. Please try again or contact support.`
showToast(`<span>${message}</span>`)
}

export async function fetcher<T>(
input: RequestInfo | URL,
init: RequestInit,
showToast: (msg: string) => void,
retries: number = 2
): Promise<T> {
const resource = new URL(input.toString()).pathname.split('/').pop() || 'resource'

for (let attempt = 0; attempt < retries; attempt++) {
try {
const res = await fetch(input, {
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
...init,
})

if (res.status === 403) {
await authService.logout(apiBase)
showErrorToast(showToast, res.status, resource)
throw new Error('Unauthorized')
}

if (!res.ok) {
showErrorToast(showToast, res.status, resource)
if (attempt === retries - 1) throw new Error(`HTTP error! status: ${res.status}`)
} else {
return await res.json()
}
} catch (error) {
if (isDev()) {
console.error('Fetch error:', { input, init, error })
}

if (attempt === retries - 1) {
showErrorToast(showToast, 0, resource)
throw error
}
}
return data;
});
};

await new Promise(resolve => setTimeout(resolve, 1000))
}

throw new Error('Fetch failed after all retries')
}