I am trying to make an axios error handler in my React application. In cases of error catching, I return a function, which in turn returns an array. But when I try to access the array, I get react error
TypeError: Cannot read properties of undefined (reading 'join')
My error handler code:
export default function requestErrorsHandler(error) {
let errors = [];
if (error.response) {
if (error.response.status === 404) {
errors = error.response.data.errors;
return errors;
}
errors.push('The server was unable to process the request');
return errors;
} if (error.request) {
errors.push('Failed to get response from server. Try again');
return errors;
}
errors.push(error.message);
return errors;
}
The function in which I make an axios request:
export const getUser = async (userName) => {
try {
const response = await server.get(`${USER}/${userName}`);
const user = response.data;
return user;
} catch (err) {
return requestErrorHandler(err);
}
};
The function in which I check for errors in the request. This is where I get the error:
useEffect(async () => {
const userData = await getUser(params.username);
if (!userData) {
return setError(userData.join('\n'));
}
...
return setError(null);
}, []);
Error text Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'join')
refers to this line: return setError(userData.join('\n'));
if you print the call to the error handler function to the console, then I get undefined
. But I don’t understand why. My handler doesn't need to be asynchronous