feat: custom error and error handling

This commit is contained in:
Vinicius Souza 2024-10-30 09:05:35 -03:00
parent 3cb08e308c
commit fa17eaa8c1
3 changed files with 29 additions and 10 deletions

View file

@ -1,10 +1,11 @@
import { Center, Heading, Image, ScrollView, Text, VStack } from '@gluestack-ui/themed';
import { Center, Heading, Image, ScrollView, Text, useToast, VStack } from '@gluestack-ui/themed';
import { useNavigation } from '@react-navigation/native';
import { Controller, useForm } from 'react-hook-form';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { api } from '@services/api';
import { AppError } from '@utils/AppError';
import BackgroundImg from '@assets/background.png';
import Logo from '@assets/logo.svg';
@ -13,7 +14,7 @@ import { AuthNavigatorRoutesProps } from '@routes/auth.routes';
import { Input } from '@components/Input';
import { Button } from '@components/Button';
import axios from 'axios';
import { ToastMessage } from '@components/ToastMessage';
type FormData = {
name: string;
@ -34,6 +35,7 @@ const signUpSchema = yup.object({
export function SignUp() {
const navigation = useNavigation<AuthNavigatorRoutesProps>();
const toast = useToast();
const {
control,
@ -48,11 +50,18 @@ export function SignUp() {
const response = await api.post('/users', { name, email, password });
console.debug(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.response?.data);
return;
}
throw error;
console.info(error);
const isAppError = error instanceof AppError;
const title = isAppError
? error.message
: 'Não foi possível criar a conta. Tente novamente mais tarde.';
toast.show({
placement: 'top',
render: ({ id }) => (
<ToastMessage id={id} action="error" onClose={() => toast.close(id)} title={title} />
),
});
}
}

View file

@ -1,5 +1,7 @@
import axios from 'axios';
import { AppError } from '@utils/AppError';
const api = axios.create({
baseURL: 'http://192.168.0.53:3333',
});
@ -14,10 +16,11 @@ api.interceptors.request.use(
);
api.interceptors.response.use(
(response) => {
return response;
},
(response) => response,
(error) => {
if (error.response && error.response.data) {
return Promise.reject(new AppError(error.response.data.message));
}
return Promise.reject(error);
},
);

7
src/utils/AppError.ts Normal file
View file

@ -0,0 +1,7 @@
export class AppError {
message: string;
constructor(message: string) {
this.message = message;
}
}