Files
frontend/src/core/utils/errorResponse.js
AmirHossein Mahmoodi 55b1f45e7c fixed bug
2025-09-29 10:35:01 +03:30

70 lines
2.5 KiB
JavaScript

"use client";
import { toast } from "react-toastify";
import {
errorAccessDeniedToast,
errorClientToast,
errorLogicToast,
errorMaxLengthToast,
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 413:
if (notification) errorMaxLengthToast(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);
}
};