Ver código fonte

Better handle of API errors

Tatiana Inama 4 anos atrás
pai
commit
3231780bd6
1 arquivos alterados com 19 adições e 11 exclusões
  1. 19 11
      utils/api.ts

+ 19 - 11
utils/api.ts

@@ -29,19 +29,27 @@ type FetchApi = <T>(
 ) => Promise<FetchApiResult>;
 
 const fetchApi: FetchApi = async (path, method, body) => {
-  const response = await fetch(`${API}${path}`, {
-    method: method,
-    body: JSON.stringify(body),
-  });
-
-  const { message, ...result } = await response.json();
-
-  if (response.ok) {
-    return { state: ApiResulState.SUCCESS, message, user: result };
-  } else {
+  try {
+    const response = await fetch(`${API}${path}`, {
+      method: method,
+      body: JSON.stringify(body),
+      headers: { "Content-Type": "application/json" },
+    });
+
+    const { message, ...result } = await response.json();
+
+    if (response.ok) {
+      return { state: ApiResulState.SUCCESS, message, user: result };
+    } else {
+      return {
+        state: ApiResulState.ERROR,
+        error: message.replace("Incorect", "Incorrect"),
+      };
+    }
+  } catch (error) {
     return {
       state: ApiResulState.ERROR,
-      error: message.replace("Incorect", "Incorrect"),
+      error: `There was an error, please try again`,
     };
   }
 };