fix: catch network error by using async

This commit is contained in:
EnixCoda 2021-05-10 01:27:15 +08:00
parent c43a5c2311
commit 314575beca
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD
2 changed files with 31 additions and 27 deletions

View file

@ -11,7 +11,7 @@ export type Props = {
accessToken: string | undefined
config: Config
loadWithPJAX(url: string): void
catchNetworkErrors: <T>(fn: () => T) => T | undefined
catchNetworkErrors: <T>(fn: () => T) => Promise<T | undefined>
}
export type ConnectorState = {

View file

@ -1,5 +1,6 @@
import { useConfigs } from 'containers/ConfigsContext'
import { errors, platformName } from 'platforms'
import { useCallback } from 'react'
import { useLoadedContext } from 'utils/hooks/useLoadedContext'
import { SideBarErrorContext } from '../../components/ErrorContext'
import { SideBarStateContext } from '../../components/SideBarState'
@ -9,33 +10,36 @@ export function useCatchNetworkError() {
const stateContext = useLoadedContext(SideBarStateContext)
const errorContext = useLoadedContext(SideBarErrorContext)
return function <T>(fn: () => T) {
try {
return fn()
} catch (err) {
if (err.message === errors.EMPTY_PROJECT) {
errorContext.onChange('This project seems to be empty.')
} else if (err.message === errors.BLOCKED_PROJECT) {
errorContext.onChange('Access to the project is blocked.')
} else if (
err.message === errors.NOT_FOUND ||
err.message === errors.BAD_CREDENTIALS ||
err.message === errors.API_RATE_LIMIT
) {
stateContext.onChange('error-due-to-auth')
} else if (err.message === errors.CONNECTION_BLOCKED) {
if (accessToken) {
errorContext.onChange(`Cannot connect to ${platformName}.`)
} else {
return useCallback(
async function <T>(fn: () => T) {
try {
return await fn() // keep the await so that catch block can catch async errors
} catch (err) {
if (err.message === errors.EMPTY_PROJECT) {
errorContext.onChange('This project seems to be empty.')
} else if (err.message === errors.BLOCKED_PROJECT) {
errorContext.onChange('Access to the project is blocked.')
} else if (
err.message === errors.NOT_FOUND ||
err.message === errors.BAD_CREDENTIALS ||
err.message === errors.API_RATE_LIMIT
) {
stateContext.onChange('error-due-to-auth')
} else if (err.message === errors.CONNECTION_BLOCKED) {
if (accessToken) {
errorContext.onChange(`Cannot connect to ${platformName}.`)
} else {
stateContext.onChange('error-due-to-auth')
}
} else if (err.message === errors.SERVER_FAULT) {
errorContext.onChange(`${platformName} server went down.`)
} else {
stateContext.onChange('disabled')
errorContext.onChange('Some thing went wrong.')
throw err
}
} else if (err.message === errors.SERVER_FAULT) {
errorContext.onChange(`${platformName} server went down.`)
} else {
stateContext.onChange('disabled')
errorContext.onChange('Some thing went wrong.')
throw err
}
}
}
},
[accessToken /* , stateContext.value, errorContext.value */],
)
}