forked from polka_billy/porridger
Added http errors handing to all fettch requests
This commit is contained in:
@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"
|
||||
|
||||
import { API_URL } from "../../config"
|
||||
import { isLiteralUnion } from "../../utils/types"
|
||||
import { handleHTTPErrors } from "../../utils"
|
||||
|
||||
const addErrors = ["Не удалось опубликовать объявление", 'Неверный ответ от сервера', 'Неизвестная ошибка'] as const
|
||||
type AddError = typeof addErrors[number]
|
||||
@ -45,6 +46,8 @@ const useAddAnnouncement = () => {
|
||||
signal: abortController.signal
|
||||
})
|
||||
|
||||
handleHTTPErrors(res)
|
||||
|
||||
const data: unknown = await res.json()
|
||||
|
||||
if (!isAddResponse(data)) throw new Error('Неверный ответ от сервера')
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { useState } from "react"
|
||||
import { API_URL } from "../../config"
|
||||
import { isConst, isObject } from "../../utils/types"
|
||||
import { handleHTTPErrors } from "../../utils"
|
||||
|
||||
interface AuthData {
|
||||
email: string,
|
||||
@ -57,6 +58,9 @@ function useAuth() {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
handleHTTPErrors(res)
|
||||
|
||||
const signupData: unknown = await res.json()
|
||||
|
||||
if (!isSignUpResponse(signupData)) {
|
||||
|
@ -4,6 +4,7 @@ import { useNavigate } from "react-router-dom"
|
||||
import { getToken } from "../../utils/auth"
|
||||
import { API_URL } from "../../config"
|
||||
import { isObject } from "../../utils/types"
|
||||
import { handleHTTPErrors } from "../../utils"
|
||||
|
||||
type BookResponse = {
|
||||
Success: boolean
|
||||
@ -39,6 +40,8 @@ function useBook(id: number) {
|
||||
}
|
||||
})
|
||||
|
||||
handleHTTPErrors(res)
|
||||
|
||||
const data: unknown = await res.json()
|
||||
|
||||
if (!isBookResponse(data)) {
|
||||
|
@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { isAborted } from '../../utils'
|
||||
|
||||
import { handleHTTPErrors, isAborted } from '../../utils'
|
||||
|
||||
const useFetch = <T>(url: string, params: RequestInit | undefined, initialData: T, dataGuard: (obj: unknown) => obj is T) => {
|
||||
const [data, setData] = useState(initialData)
|
||||
@ -18,17 +19,7 @@ const useFetch = <T>(url: string, params: RequestInit | undefined, initialData:
|
||||
|
||||
fetch(url, { ...params, signal: abortControllerRef.current.signal })
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
switch (res.status) {
|
||||
case 401:
|
||||
throw new Error("Ошибка авторизации")
|
||||
case 404:
|
||||
throw new Error("Объект не найден")
|
||||
default: {
|
||||
throw new Error("Ошибка ответа от сервера")
|
||||
}
|
||||
}
|
||||
}
|
||||
handleHTTPErrors(res)
|
||||
|
||||
return res.json()
|
||||
})
|
||||
|
Reference in New Issue
Block a user