Files
Frontend/src/core/utils/errorResponse.js
AmirHossein Mahmoodi 9bcddb6610 Feature/migration
2025-05-05 09:57:50 +00:00

73 lines
2.0 KiB
JavaScript

"use client";
import { toast } from "react-toastify";
import {
errorAccessDeniedToast,
errorClientToast,
errorLogicToast,
errorServerToast,
errorTooManyToast,
errorUnauthorizedToast,
errorValidationToast,
} from "@/core/components/Toasts/error";
const isServerError = (status) => status >= 500 && status <= 599;
const isClientError = (status) => status >= 400 && status <= 499;
const errorServer = (response, notification, toastContainer) => {
if (notification) errorServerToast(toastContainer);
};
const errorClient = (response, notification, toastContainer, logout) => {
switch (response.status) {
case 401:
logout();
if (notification) errorUnauthorizedToast(toastContainer);
break;
case 403:
if (notification)
errorAccessDeniedToast(response.data.message, toastContainer);
break;
case 422:
if ("type" in response.data) {
if (Array.isArray(response.data.message)) {
response.data.message.map((item) => {
if (notification) errorLogicToast(item, toastContainer);
});
} else {
if (notification)
errorLogicToast(response.data.message, toastContainer);
}
break;
}
if (notification) {
const errorsMap = Object.keys(response.data.errors);
const errorsArray = response.data.errors;
errorsMap.map((item, index) => {
errorValidationToast(errorsArray[item][0], toastContainer);
});
}
break;
case 429:
if (notification) errorTooManyToast(toastContainer);
break;
default:
if (notification) errorClientToast(toastContainer);
break;
}
};
export const errorResponse = (
response,
notification,
toastContainer,
logout,
) => {
if (notification) toast.dismiss({ containerId: toastContainer });
if (isServerError(response.status)) {
errorServer(response, notification, toastContainer);
} else if (isClientError(response.status)) {
errorClient(response, notification, toastContainer, logout);
}
};