Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api error): backend API error handling #70

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ New features, fixed bugs, known defects and other noteworthy changes to each rel

### Change
* updated translations
* Status error code api error handling

### Technical Support
* Build images also for arm64, in addition to amd64
Expand Down
2 changes: 1 addition & 1 deletion src/components/cax-companyData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const CompanyDataCax = ({
const applicationId = obj['applicationId']

useEffect(() => {
dispatch(getCompanyDetailsWithAddress(applicationId))
dispatch(getCompanyDetailsWithAddress({applicationId, dispatch}))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the old way to do api calls - also it is considered bad practice to call dispatch from a Redux action. See answers in https://stackoverflow.com/a/41260990/830067

convert the redux code to the new apiSlice way as has been done in the portal frontend and then use

const { data, error } = useGetCompanyDetailsWithAddressQuery(applicationId)

outside of the useEffect. We can also handle the error here instead of the unnecessary statusCodeError.ts

}, [dispatch])

useEffect(() => {
Expand Down
4 changes: 2 additions & 2 deletions src/components/cax-companyRole.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ export const CompanyRoleCax = ({
const dispatch = useDispatch()

useEffect(() => {
dispatch(fetchAgreementData())
dispatch(fetchAgreementConsents(applicationId))
dispatch(fetchAgreementData(dispatch))
dispatch(fetchAgreementConsents({applicationId, dispatch}))
}, [dispatch])

useEffect(() => {
Expand Down
23 changes: 23 additions & 0 deletions src/components/cax-registration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
fetchId,
updateInvitation,
} from '../state/features/application/actions'
import { statusCodeSelector } from '../state/features/statusCodeError'
interface RegistrationCaxProps {
currentActiveStep: number
}
Expand All @@ -52,6 +53,28 @@ export const RegistrationCax = ({
const dispatch = useDispatch()
const { status, error } = useSelector(applicationSelector)

const errorCode = useSelector(statusCodeSelector)

const getErrorMessage = (errorCode: number) => {
console.log('errorCode', typeof errorCode)
switch (errorCode){
case 400:
case 404:
return t('ErrorMessage.connectAdministrator')
case 401:
case 403:
return t('ErrorMessage.missingPermissions')
case 409:
return t('ErrorMessage.connectAdministrator')
default:
return t('ErrorMessage.defaultReload')
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too complicated. write simply as:

const getErrorMessage = (errorCode: number) => t(\ErrorMessage.${errorCode}`

and then add descriptions in the jsons like

"ErrorMessage": {
"400": "...",
"401": "...",
etc.


useEffect(() => {
errorCode && toast.error(getErrorMessage(errorCode))
},[errorCode])

if (error) {
toast.error(error)
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/cax-responsibilities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ export const ResponsibilitiesCax = ({
}

useEffect(() => {
dispatch(fetchRolesComposite())
dispatch(fetchInvited(applicationId))
dispatch(fetchRolesComposite(dispatch))
dispatch(fetchInvited({applicationId, dispatch}))
}, [dispatch])

useEffect(() => {
Expand Down
4 changes: 2 additions & 2 deletions src/components/dragdrop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const DragDrop = ({ currentActiveStep }: DragDropProps) => {

useEffect(() => {
if(!error && !documentError){
dispatch(fetchDocuments(applicationId))
dispatch(fetchDocuments({applicationId, dispatch}))
}
}, [dispatch, deleteRequest, uploadRequest])

Expand Down Expand Up @@ -152,7 +152,7 @@ export const DragDrop = ({ currentActiveStep }: DragDropProps) => {
documentId: string,
documentName: string
) => {
dispatch(fetchDocumentByDocumentId({ documentId, documentName }))
dispatch(fetchDocumentByDocumentId({ documentId, documentName, dispatch }))
}

return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/verifyRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ export const VerifyRegistration = ({
}

const hasRoles = () => {
return true
return registrationData.companyRoles.length > 0
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please also remove the { return * }

const hasRoles = () => registrationData.companyRoles.length > 0

const hasDocuments = () => {
return documents && documents.length > 0 ? true : false
return documents && documents.length > 0
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write as

const hasDocuments = () => documents && documents.length > 0


return (
Expand Down
5 changes: 4 additions & 1 deletion src/locales/de/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,10 @@
"default": "This Page isn't working.",
"error1": "Registration form cant get submitted, since company data are missing. Please fill out all company data in Step 1.",
"error2": "Registration form cant get submitted. CX Terms and Conditions need to get accepted. Please accept the Terms and Conditions under Step 3 to proceed.",
"error3": "Registration form cant get submitted. Please upload your company document under Step 4."
"error3": "Registration form cant get submitted. Please upload your company document under Step 4.",
"connectAdministrator": "Something went wrong, please connect your administrator",
"missingPermissions": "Missing permissions, please connect your administrator",
"defaultReload": "Something went wrong, please reload and connect your administrator if the issue appears again"
},
"FooterContent": {
"Footer1": "Please enter all the required information before proceeding.",
Expand Down
5 changes: 4 additions & 1 deletion src/locales/en/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,10 @@
"default": "This Page isn't working.",
"error1": "Registration form cant get submitted, since company data are missing. Please fill out all company data in Step 1.",
"error2": "Registration form cant get submitted. CX Terms and Conditions need to get accepted. Please accept the Terms and Conditions under Step 3 to proceed.",
"error3": "Registration form cant get submitted. Please upload your company document under Step 4."
"error3": "Registration form cant get submitted. Please upload your company document under Step 4.",
"connectAdministrator": "Something went wrong, please connect your administrator",
"missingPermissions": "Missing permissions, please connect your administrator",
"defaultReload": "Something went wrong, please reload and connect your administrator if the issue appears again"
},
"FooterContent": {
"Footer1": "Please enter all the required information before proceeding.",
Expand Down
9 changes: 6 additions & 3 deletions src/state/features/application/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import { createAsyncThunk } from '@reduxjs/toolkit'
import { Dispatch, createAsyncThunk } from '@reduxjs/toolkit'
import { ApplicationApi } from './api'
import { ApplicationStatus, CompanyDetails, name } from './types'
import { setStatusCode } from '../statusCodeError'

const fetchId = createAsyncThunk(`${name}/fetchId`, async () => {
try {
Expand Down Expand Up @@ -61,13 +62,15 @@ const updateStatus = createAsyncThunk(

const getCompanyDetailsWithAddress = createAsyncThunk(
`${name}/companyDetailsWithAddress/get`,
async (applicationId: string) => {
async ({applicationId, dispatch}: {applicationId: string, dispatch: Dispatch}) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as written in the other comment convert this to an RTK Query apiSlice and don't use dispatch inside another redux reducer. We can then handle the error outside of the Redux code as shown in another comment

try {
dispatch(setStatusCode({ errorCode: '' }))
return await ApplicationApi.getInstance().getCompanyDetailsWithAddress(
applicationId
)
} catch (error: unknown) {
} catch (error: any) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't use try { ... } catch (error: any) {...} here - instead convert this into a RTK Query apiSlice with built in error handling

console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error(
'No active company application existing. Please contact the administrator.'
)
Expand Down
17 changes: 11 additions & 6 deletions src/state/features/applicationCompanyRole/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,33 @@
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import { createAsyncThunk } from '@reduxjs/toolkit'
import { Dispatch, createAsyncThunk } from '@reduxjs/toolkit'
import { API } from './api'
import { setStatusCode } from '../statusCodeError'

const fetchAgreementData = createAsyncThunk(
'registration/application/user/fetchAgreementData',
async () => {
async (dispatch: Dispatch) => {
try {
dispatch(setStatusCode({ errorCode: '' }))
return await API.getInstance().companyRoleAgreementData()
} catch (error: unknown) {
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error('fetchCompanyRole api call error')
}
}
)

const fetchAgreementConsents = createAsyncThunk(
'registration/application/user/fetchAgreementConsents',
async (appId: string) => {
async ({applicationId, dispatch}: {applicationId: string, dispatch: Dispatch}) => {
try {
return await API.getInstance().companyRoleAgreementConsents(appId)
} catch (error: unknown) {
dispatch(setStatusCode({ errorCode: '' }))
return await API.getInstance().companyRoleAgreementConsents(applicationId)
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error('fetchCompanyRole api call error')
}
}
Expand Down
14 changes: 10 additions & 4 deletions src/state/features/applicationDocuments/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { Api } from './api'
import { DocumentType } from './types'
import { ProgressType } from '../../../types/MainTypes'
import { downloadDocument } from '../../../helpers/utils'
import { setStatusCode } from '../statusCodeError'

const handleUpdateProgress = (
progress: ProgressType,
Expand All @@ -39,14 +40,16 @@ const handleUpdateProgress = (

const fetchDocuments = createAsyncThunk(
'registration/application/user/fetchDocuments',
async (applicationId: string) => {
async ({applicationId, dispatch}: {applicationId: string, dispatch: Dispatch}) => {
try {
dispatch(setStatusCode({ errorCode: '' }))
return await Api.getInstance().getDocuments(
applicationId,
DocumentType.COMMERCIAL_REGISTER_EXTRACT
)
} catch (error: unknown) {
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error('Unable to load documents. Please contact the administrator.')
}
}
Expand All @@ -57,18 +60,21 @@ const fetchDocumentByDocumentId = createAsyncThunk(
async ({
documentId,
documentName,
dispatch
}: {
documentId: string
documentName: string
dispatch: Dispatch
}) => {
try {
const { data, headers } = await Api.getInstance().getDocumentByDocumentId(
documentId
)

dispatch(setStatusCode({ errorCode: '' }))
return downloadDocument(data, headers['content-type'], documentName)
} catch (error: unknown) {
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error(
'Unable to download document. Please contact the administrator.'
)
Expand Down
15 changes: 10 additions & 5 deletions src/state/features/applicationInviteUser/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,38 @@
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import { createAction, createAsyncThunk } from '@reduxjs/toolkit'
import { Dispatch, createAction, createAsyncThunk } from '@reduxjs/toolkit'
import { Api } from './api'
import { InviteNewUser } from './types'
import { setStatusCode } from '../statusCodeError'

const setUserToInvite = createAction<InviteNewUser>(
'registration/application/user/setUserToInvite'
)

const fetchRolesComposite = createAsyncThunk(
'registration/application/user/fetchRoles',
async () => {
async (dispatch: Dispatch) => {
try {
dispatch(setStatusCode({ errorCode: '' }))
return await Api.getInstance().getRolesComposite()
} catch (error: unknown) {
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error('Unable to load roles. Please contact the administrator.')
}
}
)

const fetchInvited = createAsyncThunk(
'registration/application/user/fetchInvited',
async (applicationId: string) => {
async ({applicationId, dispatch}: {applicationId: string, dispatch: Dispatch}) => {
try {
dispatch(setStatusCode({ errorCode: '' }))
return await Api.getInstance().getInvitedUsers(applicationId)
} catch (error: unknown) {
} catch (error: any) {
console.error('api call error:', error)
dispatch(setStatusCode({ errorCode: error.response.status }))
throw Error(
'Application ID not existing. Please contact the administrator.'
)
Expand Down
2 changes: 2 additions & 0 deletions src/state/features/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import documentSlice from './applicationDocuments/slice'
import user from './user/reducer'
import roleSlice from './applicationCompanyRole/slice'
import registrationData from './applicationVerifyRegister/slice'
import statusCodeErrorSlice from './statusCodeError'

export const reducers = {
application: applicationSlice.reducer,
Expand All @@ -33,6 +34,7 @@ export const reducers = {
document: documentSlice.reducer,
registrationData: registrationData.reducer,
user,
statuscode: statusCodeErrorSlice.reducer
}

const rootReducer = combineReducers(reducers)
Expand Down
45 changes: 45 additions & 0 deletions src/state/features/statusCodeError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/********************************************************************************
* Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import { createSlice } from '@reduxjs/toolkit'
import type { RootState } from '../store'

const name = 'statuscode'

const initialState = {
errorCode: null,
}

export const slice = createSlice({
name,
initialState,
reducers: {
setStatusCode: (state, { payload }) => ({
...state,
...payload,
})
},
})

export const { setStatusCode } = slice.actions

export const statusCodeSelector = (state: RootState): number =>
state.statuscode.errorCode

export default slice
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this file because we can handle errors the RTK Query way