Files
SHiNE-server/shine-UI/js/services/ui-error-texts.js
T

198 lines
6.8 KiB
JavaScript
Raw 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 { getLanguage, t } from '../i18n/index.js';
import { isDeveloperToolsEnabled } from './feature-settings.js';
// Сетевые ошибки браузера (fetch, загрузка файла) – одним понятным текстом.
const NETWORK_ERROR_RE = /failed to fetch|networkerror|network error|load failed|network request failed|net::err_|err_internet_disconnected/;
const noConnectionText = () => t('errors.text_001');
const HAS_CYRILLIC_RE = /[а-яё]/i;
function extractCode(message = '') {
const match = String(message || '').match(/\(([A-Z0-9_]+)\)\s*$/i);
return match ? String(match[1]).toUpperCase() : '';
}
function normalizeText(error) {
return String(error?.message || '').trim().toLowerCase();
}
export function toUserMessage(error, fallback = t('errors.text_002')) {
const raw = String(error?.message || '').trim();
const text = normalizeText(error);
const code = String(error?.code || extractCode(raw) || '').toUpperCase();
if (
text.includes('webcrypto') ||
text.includes('crypto.subtle') ||
text.includes("reading 'digest'") ||
text.includes('not supported on insecure origins')
) {
return t('errors.text_003');
}
if (
text.includes('mixed content') ||
text.includes('insecure websocket connection') ||
(text.includes('https') && text.includes('ws://'))
) {
return t('errors.text_004');
}
if (
text.includes('не удалось подключиться') ||
text.includes('failed to connect websocket') ||
text.includes('websocket закрыто') ||
text.includes('соединение websocket закрыто')
) {
return noConnectionText();
}
if (NETWORK_ERROR_RE.test(text)) {
return noConnectionText();
}
if (text.includes('таймаут') || text.includes('timeout waiting')) {
return t('errors.text_005');
}
if (
code === 'USER_NOT_FOUND' ||
text.includes('user not found') ||
text.includes('пользователь не найден')
) {
return t('errors.text_006');
}
if (code === 'DEVICE_KEY_NOT_ACTUAL') {
return t('errors.text_007');
}
if (code === 'USER_NOT_LOCAL') {
return t('errors.text_008');
}
if (code === 'PAIRING_NO_TRUSTED_SESSION_ONLINE') {
return t('errors.text_009');
}
if (code === 'PAIRING_NOT_AVAILABLE') {
return t('errors.text_010');
}
if (code === 'PAIRING_PASSWORD_INVALID') {
return t('errors.text_011');
}
if (
code === 'PREMIUMLOGIN' ||
text.includes('premiumlogin') ||
text.includes('error code: premiumlogin') ||
text.includes('логин относится к платным')
) {
return t('errors.text_012');
}
if (
code === 'TRADEMARKLOGINREQUIRESREVIEW' ||
text.includes('trademarkloginrequiresreview') ||
text.includes('companyloginrequiresreview') ||
text.includes('логин компании') ||
text.includes('логин относится к компаниям') ||
text.includes('требует отдельного согласования')
) {
return t('errors.text_013');
}
if (
code === 'BAD_CHANNEL_NAME' ||
text.includes('channel name must match') ||
text.includes('channelname contains unsupported') ||
text.includes('channelname must not contain only digits') ||
text.includes('channelname length must be 4..32') ||
text.includes('channelname length must be 3..32') ||
text.includes('channelname length must be 1..32') ||
text.includes('bad_channel_name')
) {
return t('errors.text_014');
}
if (text.includes('channel name is required') || text.includes('введите имя канала')) {
return t('errors.text_015');
}
if (code === 'CHANNEL_NAME_ALREADY_EXISTS' || text.includes('channel_name_already_exists')) {
return t('errors.text_016');
}
if (
code === 'PREV_LINE_BLOCK_NOT_FOUND' ||
code === 'LINE_ERR_NO_PREV' ||
text.includes('prev_line_block_not_found') ||
text.includes('line_err_no_prev')
) {
return t('errors.text_017');
}
if (
code === 'BAD_PREV_LINE_HASH' ||
code === 'LINE_ERR_PREV_HASH_MISMATCH' ||
text.includes('bad_prev_line_hash') ||
text.includes('line_err_prev_hash_mismatch') ||
text.includes('prevlinehash')
) {
return t('errors.text_018');
}
if (code === 'LINE_ERR_PARTIAL_FIELDS' || text.includes('line_err_partial_fields')) {
return t('errors.text_019');
}
if (code === 'NOT_AUTHENTICATED' || text.includes('session is not ready for signing')) {
return t('errors.text_020');
}
if (
code === 'SESSION_NOT_FOUND' ||
code === 'SESSION_KEY_NOT_ACTUAL' ||
code === 'SESSION_OF_ANOTHER_USER'
) {
return t('errors.text_021');
}
if (code === 'UNSUPPORTED_KEY_ALGORITHM' || text.includes('unsupported key algorithm')) {
return t('errors.text_022');
}
if (!raw) return fallback;
// Internal exceptions may contain Russian text even when the UI is in English.
// Do not leak untranslated technical messages into the interface.
if (getLanguage() !== 'ru' && HAS_CYRILLIC_RE.test(raw)) {
return fallback || t('remaining.errors.generic');
}
return raw;
}
// Ошибка действия для тоста или строки статуса: что не получилось и, если её можно объяснить
// человеку, – почему. «Не удалось удалить чат. Нет связи с сервером…» вместо
// «Не удалось удалить чат: TypeError: Failed to fetch». Технический текст остаётся в журнале,
// а на экране виден только с включёнными инструментами разработчика.
export function actionErrorText(action, error) {
const raw = String(error?.message || '').trim();
const human = toUserMessage(error, '');
if (human && human !== raw) return `${action}. ${human}`;
if (raw && HAS_CYRILLIC_RE.test(raw)) {
return /^(не удалось|ошибка|нельзя|сначала)/i.test(raw) ? raw : `${action}: ${raw}`;
}
if (raw && isDeveloperToolsEnabled()) return `${action}: ${raw}`;
return t('remaining.errors.try_again', { action });
}
// Микрофон и камера (getUserMedia): у этих ошибок смысл несёт имя, а не текст. Имена общие
// для разных API браузера, поэтому разбираются только там, где запрашивали микрофон/камеру.
export function mediaAccessErrorText(error) {
const name = String(error?.name || '');
if (name === 'NotAllowedError' || name === 'SecurityError') return t('errors.text_023');
if (name === 'NotFoundError' || name === 'OverconstrainedError') return t('errors.text_024');
if (name === 'NotReadableError' || name === 'AbortError') return t('errors.text_025');
return '';
}