better error handling

This commit is contained in:
spencerwooo 2022-01-10 16:36:45 +08:00
parent aa3986cb76
commit 02f03b41bf
3 changed files with 49 additions and 38 deletions

View file

@ -184,14 +184,14 @@ const FileListing: FC<{ query?: ParsedUrlQuery }> = ({ query }) => {
console.log(error)
// If error includes 403 which means the user has not completed initial setup, redirect to OAuth page
if (error.message.includes('403')) {
if (error.status === 403) {
router.push('/onedrive-vercel-index-oauth/step-1')
return <div></div>
}
return (
<PreviewContainer>
{error.message.includes('401') ? <Auth redirect={path} /> : <FourOhFour errorMsg={error.message} />}
{error.status === 401 ? <Auth redirect={path} /> : <FourOhFour errorMsg={JSON.stringify(error.message)} />}
</PreviewContainer>
)
}

View file

@ -178,39 +178,46 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// Querying current path identity (file or folder) and follow up query childrens in folder
// console.log(accessToken)
const { data: identityData } = await axios.get(requestUrl, {
headers: { Authorization: `Bearer ${accessToken}` },
params: {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
},
})
if ('folder' in identityData) {
const { data: folderData } = await axios.get(`${requestUrl}${isRoot ? '' : ':'}/children`, {
try {
const { data: identityData } = await axios.get(requestUrl, {
headers: { Authorization: `Bearer ${accessToken}` },
params: next
? {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
top: siteConfig.maxItems,
$skipToken: next,
}
: {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
top: siteConfig.maxItems,
},
params: {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
},
})
// Extract next page token from full @odata.nextLink
const nextPage = folderData['@odata.nextLink'] ? folderData['@odata.nextLink'].match(/&\$skiptoken=(.+)/i)[1] : null
if ('folder' in identityData) {
const { data: folderData } = await axios.get(`${requestUrl}${isRoot ? '' : ':'}/children`, {
headers: { Authorization: `Bearer ${accessToken}` },
params: next
? {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
top: siteConfig.maxItems,
$skipToken: next,
}
: {
select: '@microsoft.graph.downloadUrl,name,size,id,lastModifiedDateTime,folder,file',
top: siteConfig.maxItems,
},
})
// Return paging token if specified
if (nextPage) {
res.status(200).json({ folder: folderData, next: nextPage })
} else {
res.status(200).json({ folder: folderData })
// Extract next page token from full @odata.nextLink
const nextPage = folderData['@odata.nextLink']
? folderData['@odata.nextLink'].match(/&\$skiptoken=(.+)/i)[1]
: null
// Return paging token if specified
if (nextPage) {
res.status(200).json({ folder: folderData, next: nextPage })
} else {
res.status(200).json({ folder: folderData })
}
return
}
res.status(200).json({ file: identityData })
return
} catch (error: any) {
res.status(error.response.status).json({ error: error.response.data })
return
}
res.status(200).json({ file: identityData })
return
}

View file

@ -4,14 +4,18 @@ import useSWR, { cache, Key, useSWRInfinite } from 'swr'
import { getStoredToken } from './protectedRouteHandler'
// Common axios fetch function for use with useSWR
export function fetcher(url: string, token?: string): Promise<any> {
return token
? axios
.get(url, {
headers: { 'od-protected-token': token },
})
.then(res => res.data)
: axios.get(url).then(res => res.data)
export async function fetcher(url: string, token?: string): Promise<any> {
try {
return (
await (token
? axios.get(url, {
headers: { 'od-protected-token': token },
})
: axios.get(url))
).data
} catch (err: any) {
throw { status: err.response.status, message: err.response.data }
}
}
/**
* Use stale SWR instead of revalidating on each request. Not ideal for this scenario but have to do