frontAnswerer/lib/utils/parse-error.ts
2024-05-31 19:41:18 +03:00

50 lines
1.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { AxiosError } from "axios";
export type ServerError = {
statusCode: number;
error: string;
message: string;
};
const translateMessage: Record<string, string> = {
"user not found": "Пользователь не найден",
"invalid password": "Неправильный пароль",
"field <password> is empty": 'Поле "Пароль" не заполнено',
"field <login> is empty": 'Поле "Логин" не заполнено',
"field <email> is empty": 'Поле "E-mail" не заполнено',
"field <phoneNumber> is empty": 'Поле "Номер телефона" не заполнено',
"user with this email or login is exist": "Пользователь уже существует",
"user with this login is exist": "Пользователь с таким логином уже существует",
};
export const parseAxiosError = (nativeError: unknown): [string, number?] => {
const error = nativeError as AxiosError;
if (error.response?.data && "statusCode" in (error.response.data as ServerError)) {
const serverError = error.response.data as ServerError;
const translatedMessage = translateMessage[serverError.message];
if (translatedMessage !== undefined) serverError.message = translatedMessage;
return [serverError.message, serverError.statusCode];
}
switch (error.status) {
case 404:
return ["Не найдено.", error.status];
case 403:
return ["Доступ ограничен.", error.status];
case 401:
return ["Ошибка авторизации.", error.status];
case 500:
return ["Внутренняя ошибка сервера.", error.status];
case 503:
return ["Сервис недоступен.", error.status];
default:
return ["Неизвестная ошибка сервера."];
}
};