| 13 | const sleep = () => new Promise(resolve => setTimeout(resolve, 1000)); |
| 14 | |
| 15 | export const baseQueryWithErrorHandling = async (args: string | FetchArgs, api: BaseQueryApi, |
| 16 | extraOptions: object) => { |
| 17 | api.dispatch(startLoading()); |
| 18 | if (import.meta.env.DEV) await sleep(); |
| 19 | const result = await customBaseQuery(args, api, extraOptions); |
| 20 | api.dispatch(stopLoading()); |
| 21 | if (result.error) { |
| 22 | console.log(result.error); |
| 23 | |
| 24 | const originalStatus = result.error.status === 'PARSING_ERROR' && result.error.originalStatus |
| 25 | ? result.error.originalStatus |
| 26 | : result.error.status |
| 27 | |
| 28 | const responseData = result.error.data as ErrorResponse; |
| 29 | |
| 30 | switch (originalStatus) { |
| 31 | case 400: |
| 32 | if (typeof responseData === 'string') toast.error(responseData); |
| 33 | else if ('errors' in responseData) { |
| 34 | throw Object.values(responseData.errors).flat().join(', ') |
| 35 | } |
| 36 | else toast.error(responseData.title); |
| 37 | break; |
| 38 | case 401: |
| 39 | if (typeof responseData === 'object' && 'title' in responseData) |
| 40 | toast.error(responseData.title); |
| 41 | break; |
| 42 | case 403: |
| 43 | if (typeof responseData === 'object') |
| 44 | toast.error('403 Forbidden'); |
| 45 | break; |
| 46 | case 404: |
| 47 | if (typeof responseData === 'object' && 'title' in responseData) |
| 48 | router.navigate('/not-found') |
| 49 | break; |
| 50 | case 500: |
| 51 | if (typeof responseData === 'object') |
| 52 | router.navigate('/server-error', { state: { error: responseData } }) |
| 53 | break; |
| 54 | default: |
| 55 | break; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return result; |
| 60 | } |