mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {useCallback} from 'react' 2import {msg} from '@lingui/macro' 3import {useLingui} from '@lingui/react' 4 5type CleanedError = { 6 raw: string | undefined 7 clean: string | undefined 8} 9 10export function useCleanError() { 11 const {_} = useLingui() 12 13 return useCallback<(error?: any) => CleanedError>( 14 error => { 15 if (!error) 16 return { 17 raw: undefined, 18 clean: undefined, 19 } 20 21 let raw = error.toString() 22 23 if (isNetworkError(raw)) { 24 return { 25 raw, 26 clean: _( 27 msg`Unable to connect. Please check your internet connection and try again.`, 28 ), 29 } 30 } 31 32 if ( 33 raw.includes('Upstream Failure') || 34 raw.includes('NotEnoughResources') || 35 raw.includes('pipethrough network error') 36 ) { 37 return { 38 raw, 39 clean: _( 40 msg`The server appears to be experiencing issues. Please try again in a few moments.`, 41 ), 42 } 43 } 44 45 if (raw.includes('Bad token scope') || raw.includes('Bad token method')) { 46 return { 47 raw, 48 clean: _( 49 msg`This feature is not available while using an app password. Please sign in with your main password.`, 50 ), 51 } 52 } 53 54 if (raw.includes('Rate Limit Exceeded')) { 55 return { 56 raw, 57 clean: _( 58 msg`You've reached the maximum number of requests allowed. Please try again later.`, 59 ), 60 } 61 } 62 63 if (raw.startsWith('Error: ')) { 64 raw = raw.slice('Error: '.length) 65 } 66 67 return { 68 raw, 69 clean: undefined, 70 } 71 }, 72 [_], 73 ) 74} 75 76const NETWORK_ERRORS = [ 77 'Abort', 78 'Network request failed', 79 'Failed to fetch', 80 'Load failed', 81] 82 83export function isNetworkError(e: unknown) { 84 const str = String(e) 85 for (const err of NETWORK_ERRORS) { 86 if (str.includes(err)) { 87 return true 88 } 89 } 90 return false 91}