Skip to content

Commit

Permalink
add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ssb-jnk committed Feb 27, 2024
1 parent febd4e4 commit 92babfc
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 31 deletions.
17 changes: 6 additions & 11 deletions src/pages/TeamMembers/TeamMembers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import PageLayout from '../../components/PageLayout/PageLayout'
import Table, { TableData } from '../../components/Table/Table'
import PageSkeleton from '../../components/PageSkeleton/PageSkeleton'

import { ErrorResponse } from '../../@types/error'

import { fetchAllTeamMembersData, TeamMembersData, User } from '../../services/teamMembers'
import { formatDisplayName } from '../../utils/utils'
import { ApiError } from '../../services/ApiError'

export default function TeamMembers() {
const accessToken = localStorage.getItem('access_token') || ''
Expand All @@ -26,7 +25,7 @@ export default function TeamMembers() {
const [teamMembersData, setTeamMembersData] = useState<TeamMembersData>()
const [teamMembersTableData, setTeamMembersTableData] = useState<TableData['data']>()
const [teamMembersTableTitle, setTeamMembersTableTitle] = useState<string>(defaultActiveTab.title)
const [error, setError] = useState<ErrorResponse | undefined>()
const [error, setError] = useState<ApiError | undefined>()
const [loading, setLoading] = useState<boolean>(true)

const prepUserData = useCallback(
Expand All @@ -52,16 +51,12 @@ export default function TeamMembers() {
if (!jwt) return
fetchAllTeamMembersData(jwt.email)
.then((response) => {
if ((response as ErrorResponse).error) {
setError(response as ErrorResponse)
} else {
setTeamMembersData(response as TeamMembersData)
setTeamMembersTableData(prepUserData(response as TeamMembersData))
}
setTeamMembersData(response as TeamMembersData)
setTeamMembersTableData(prepUserData(response as TeamMembersData))
})
.finally(() => setLoading(false))
.catch((error) => {
setError(error.toString())
setError(error as ApiError)
})
}, [prepUserData])

Check warning on line 61 in src/pages/TeamMembers/TeamMembers.tsx

View workflow job for this annotation

GitHub Actions / build

React Hook useEffect has a missing dependency: 'jwt'. Either include it or remove the dependency array

Expand Down Expand Up @@ -96,7 +91,7 @@ export default function TeamMembers() {
function renderErrorAlert() {
return (
<Dialog type='warning' title='Could not fetch users'>
{error}
{`${error?.code} - ${error?.message}`}
</Dialog>
)
}
Expand Down
6 changes: 3 additions & 3 deletions src/services/ApiError.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export class ApiError extends Error {
public statusCode: number
public code: number

constructor(statusCode: number, message: string) {
constructor(code: number, message: string) {
super(message)
this.name = 'ApiError'
this.statusCode = statusCode
this.code = code
}
}
62 changes: 45 additions & 17 deletions src/services/teamMembers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ErrorResponse } from '../@types/error'
import { ApiError } from './ApiError'

const DAPLA_TEAM_API_URL = import.meta.env.VITE_DAPLA_TEAM_API_URL
Expand Down Expand Up @@ -52,19 +51,26 @@ const fetchManagedUsers = async (accessToken: string, principalName: string): Pr
})

if (!response.ok) {
// TODO: Test that it actually works
const errorMessage = (await response.text()) || 'An error occurred'
throw new ApiError(response.status, errorMessage)
const { detail, status } = JSON.parse(errorMessage)
throw new ApiError(status, detail)
}

const jsonData = await response.json()

if (!jsonData) throw new Error('No json data returned')
if (!jsonData) throw new ApiError(500, 'No json data returned')
if (!jsonData._embedded || !jsonData._embedded.managed_users) return [] // return an empty list if the user does not have any managed_users

return jsonData._embedded.managed_users
} catch (error) {
throw error
if (error instanceof ApiError) {
console.error('Failed to fetch managed users:', error)
throw error
} else {
const apiError = new ApiError(500, 'An unexpected error occurred')
console.error('Failed to fetch managed users:', apiError)
throw apiError
}
}
}

Expand Down Expand Up @@ -100,7 +106,8 @@ export const fetchManagersManagedUsers = async (accessToken: string, principalNa

if (!response.ok) {
const errorMessage = (await response.text()) || 'An error occurred'
throw new ApiError(response.status, errorMessage)
const { detail, status } = JSON.parse(errorMessage)
throw new ApiError(status, detail)
}

const jsonData = await response.json()
Expand All @@ -116,8 +123,14 @@ export const fetchManagersManagedUsers = async (accessToken: string, principalNa

return { users: formattedUsers }
} catch (error) {
console.error('Failed to fetch managed users:', error)
throw error
if (error instanceof ApiError) {
console.error('Failed to fetch managed users:', error)
throw error
} else {
const apiError = new ApiError(500, 'An unexpected error occurred')
console.error('Failed to fetch managed users:', apiError)
throw apiError
}
}
}

Expand Down Expand Up @@ -149,13 +162,14 @@ export const fetchAllUsers = async (accessToken: string): Promise<UsersData> =>

if (!response.ok) {
const errorMessage = (await response.text()) || 'An error occurred'
throw new ApiError(response.status, errorMessage)
const { detail, status } = JSON.parse(errorMessage)
throw new ApiError(status, detail)
}

const jsonData = await response.json()

if (!jsonData) throw new Error('No json data returned')
if (!jsonData._embedded || !jsonData._embedded.users) throw new Error('Did not receive users data')
if (!jsonData) throw new ApiError(500, 'No json data returned')
if (!jsonData._embedded || !jsonData._embedded.users) throw new ApiError(500, 'Did not receive users data')

const transformedData = jsonData._embedded.users.map((user: any) => {

Check failure on line 174 in src/services/teamMembers.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const userFormatted = {
Expand All @@ -169,16 +183,24 @@ export const fetchAllUsers = async (accessToken: string): Promise<UsersData> =>

return { users: transformedData }
} catch (error) {
console.error('Failed to fetch all users:', error)
throw error
if (error instanceof ApiError) {
console.error('Failed to fetch all users:', error)
throw error
} else {
const apiError = new ApiError(500, 'An unexpected error occurred')
console.error('Failed to fetch all users:', apiError)
throw apiError
}
}
}

export const fetchAllTeamMembersData = async (principalName: string): Promise<TeamMembersData | ErrorResponse> => {
export const fetchAllTeamMembersData = async (principalName: string): Promise<TeamMembersData | ApiError> => {
const accessToken = localStorage.getItem('access_token')
if (!accessToken) {
console.error('No access token available')
throw new Error('No access token available')
const apiError = new ApiError(401, 'No access token available')
console.error('Failed to fetch team members data:', apiError)
throw apiError
}

try {
Expand All @@ -189,7 +211,13 @@ export const fetchAllTeamMembersData = async (principalName: string): Promise<Te

return { myUsers: myUsers, allUsers: allUsers } as TeamMembersData
} catch (error) {
console.error('Failed to fetch all data for teamMembers:', error)
throw error
if (error instanceof ApiError) {
console.error('Failed to fetch team members data:', error)
throw error
} else {
const apiError = new ApiError(500, 'An unexpected error occurred while fetching team members data')
console.error('Failed to fetch team members data:', apiError)
throw apiError
}
}
}

0 comments on commit 92babfc

Please sign in to comment.