Skip to content

Commit

Permalink
27 - axios error and toast
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasGarcez committed Sep 21, 2024
1 parent 58beb5a commit cf566a1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/screens/app/EditPasswordScreen/EditPasswordScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';

import {useAuthUpdatePassword} from '@domain';
import {zodResolver} from '@hookform/resolvers/zod';
import {useToastService} from '@services';
import {useForm} from 'react-hook-form';

import {Button, FormPasswordInput, Screen} from '@components';
Expand All @@ -16,7 +17,12 @@ const defaultValues: EditPasswordSchema = {
};

export function EditPasswordScreen({}: AppScreenProps<'EditPasswordScreen'>) {
const {isLoading, updatePassword} = useAuthUpdatePassword();
const {showToast} = useToastService();
const {isLoading, updatePassword} = useAuthUpdatePassword({
onError: message => {
showToast({message, type: 'error'});
},
});

const {control, formState, handleSubmit} = useForm<EditPasswordSchema>({
resolver: zodResolver(editPasswordSchema),
Expand Down
30 changes: 30 additions & 0 deletions src/utils/errorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import axios from 'axios';

type ErrorWithMessage = {
message: string;
};
Expand Down Expand Up @@ -31,7 +33,35 @@ function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
* Reference: https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
*/
function getErrorMessage(error: unknown) {
const axiosErrorMessage = tryGetAxiosErrorMessage(error);
if (axiosErrorMessage) {
return axiosErrorMessage;
}
return toErrorWithMessage(error).message;
}

function tryGetAxiosErrorMessage(error: unknown): string | null {
try {
if (axios.isAxiosError(error)) {
const response = error.response;

if (response && response.data && response.data.message) {
return response.data.message;
}

if (response && response.data && Array.isArray(response.data.errors)) {
return response.data.errors
.map(
(errorObj: {message?: string}) =>
errorObj.message || 'unknown error',
)
.join(', ');
}
}
return null;
} catch (err) {
return null;
}
}

export const errorUtils = {getErrorMessage};

0 comments on commit cf566a1

Please sign in to comment.