'Return Postman error message to user on failed login/reg React-Native
My backend is set up with validations, which I want to return to the user on failed attempts.The top picture is what I am currently returning. The picture below that one (what my postman returns) is one such error message I want to return to a user on a failed login attempt in my try/catch block. I would prefer to do this via the Alert.alert() method. The following is my loginUser code:
enter code hexport interface LoginRequest {
name: string;
pass: string;
}
export const loginUser = async (
request: LoginRequest,
onSuccess: (user: User) => void,
onError: (error: any) => void,
) => {
console.log(request);
try {
await logout();
const loginResponse: AxiosResponse<LoginResponse> = await login(request);
const loginResponseData: LoginResponse = loginResponse.data;
console.log('userAuth: ', loginResponseData);
await AsyncStorage.setItem('access_token', loginResponseData.access_token);
await AsyncStorage.setItem('logout_token', loginResponseData.logout_token);
await AsyncStorage.setItem('csrf_token', loginResponseData.csrf_token);
const userId = loginResponseData.current_user.uid;
const userResponse: AxiosResponse<User> = await getUser(userId);
console.log('user response:', userResponse);
onSuccess(userResponse.data);
} catch (error: any) {
console.log('Login error: ' + JSON.stringify(error));
console.log();
onError(error);
}
};
Solution 1:[1]
You can access the body of the response of an Axios 4xx error with error.response.data. Simply use the below line:
onError(error?.response?.data?.message || error);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ridvanaltun |


