All files / backend/helpers errorText.ts

100% Statements 23/23
96.15% Branches 25/26
100% Functions 3/3
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                2x     2x                   15x       28x 6x   22x 3x   19x 1x   18x 18x 7x   11x 4x 2x 2x     9x 9x 1x   8x 2x   6x    
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
export const UNKNOWN_ERROR_TEXT = 'Unknown error';
 
// Глубина разбора вложенных ошибок: защищает от циклических cause
const MAX_NESTING = 3;
 
/**
 * Текст ошибки для лога и для отчёта о загрузке. Никогда не пустой.
 *
 * Полагаться на message нельзя: при отказе в соединении с localhost (попытки по IPv6 и IPv4) axios
 * отдаёт AxiosError с name AggregateError и пустым message, а причины лежат в errors и cause.
 * Порядок: message, тексты вложенных errors, cause, code, name.
 */
export function describeError(error: unknown): string {
    return describe(error, 0) || UNKNOWN_ERROR_TEXT;
}
 
function describe(error: unknown, depth: number): string {
    if (error === null || error === undefined) {
        return '';
    }
    if (typeof error !== 'object') {
        return String(error).trim();
    }
    if (depth > MAX_NESTING) {
        return '';
    }
    const {message, errors, cause, code, name} = error as Record<string, unknown>;
    if (typeof message === 'string' && message.trim()) {
        return message.trim();
    }
    if (Array.isArray(errors)) {
        const nested = [...new Set(errors.map((item) => describe(item, depth + 1)).filter(Boolean))];
        Eif (nested.length > 0) {
            return nested.join('; ');
        }
    }
    const causeText = describe(cause, depth + 1);
    if (causeText) {
        return causeText;
    }
    if (typeof code === 'string' && code) {
        return code;
    }
    return typeof name === 'string' ? name : '';
}