All files / http http-error-mapper.service.ts

100% Statements 51/51
90.9% Branches 60/66
100% Functions 4/4
100% Lines 49/49

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154  2x                                               2x         24x 24x   24x                             24x 2x       22x 1x       21x 1x       20x 3x       17x 1x       16x 3x       13x 1x       12x 6x       6x 6x 3x     3x               7x     7x   2x 1x     1x 1x         5x 1x     4x             3x   3x 2x 2x 2x 1x   1x 1x 1x 1x 1x 1x 1x 1x               1x      
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
 
/**
 * Extracted error info for consistent handling
 */
export interface MappedHttpError {
    /** User-friendly message to display */
    message: string;
    /** Original HTTP status code */
    status: number;
    /** Whether this is a network/connectivity error (status 0) */
    isNetworkError: boolean;
    /** Whether this is a server error (5xx) */
    isServerError: boolean;
    /** Whether this is a client error (4xx) */
    isClientError: boolean;
}
 
/**
 * Service for mapping HTTP errors to user-friendly messages.
 *
 * Can be extended/overridden for custom error messages or i18n.
 */
@Injectable({ providedIn: 'root' })
export class HttpErrorMapperService {
    /**
     * Maps an HttpErrorResponse to a user-friendly error structure.
     */
    mapError(err: HttpErrorResponse): MappedHttpError {
        const status = err.status;
        const message = this.getErrorMessage(err);
 
        return {
            message,
            status,
            isNetworkError: status === 0,
            isServerError: status >= 500,
            isClientError: status >= 400 && status < 500,
        };
    }
 
    /**
     * Gets a user-friendly error message for the given HTTP error.
     * Override this method to customize messages or add i18n support.
     */
    protected getErrorMessage(err: HttpErrorResponse): string {
        // Network error (no connection, CORS, etc.)
        if (err.status === 0) {
            return 'Сетевая ошибка. Проверьте подключение к интернету.';
        }
 
        // Authentication required
        if (err.status === 401) {
            return 'Требуется авторизация.';
        }
 
        // Forbidden
        if (err.status === 403) {
            return 'Доступ запрещен.';
        }
 
        // Not found
        if (err.status === 404) {
            return 'Не найдено.';
        }
 
        // Conflict (e.g., duplicate entry)
        if (err.status === 409) {
            return 'Объект уже существует или был модифицирован.';
        }
 
        // Validation error
        if (err.status === 422) {
            return this.extractValidationMessage(err) || 'Ошибка валидации.';
        }
 
        // Rate limiting
        if (err.status === 429) {
            return 'Слишком много запросов. Подождите и повторите запрос позже.';
        }
 
        // Server errors
        if (err.status >= 500) {
            return 'Ошибка на сервере. Попробуйте позже.';
        }
 
        // Try to extract backend message for other errors
        const backendMessage = this.extractBackendMessage(err);
        if (backendMessage) {
            return backendMessage;
        }
 
        return 'Неожиданная ошибка.';
    }
 
    /**
     * Attempts to extract a message from the backend response.
     * Override for custom API response structures.
     */
    protected extractBackendMessage(err: HttpErrorResponse): string | undefined {
        const error = err.error;
 
        // Handle common API response structures
        if (typeof error === 'object' && error) {
            // { message: "..." }
            if ('message' in error && typeof error.message === 'string' && error.message.length > 0) {
                return error.message;
            }
            // { error: "..." }
            Eif ('error' in error && typeof error.error === 'string' && error.error.length > 0) {
                return error.error;
            }
        }
 
        // Handle plain string error
        if (typeof error === 'string' && error.length > 0 && error.length < 200) {
            return error;
        }
 
        return undefined;
    }
 
    /**
     * Extracts validation error details for 422 responses.
     */
    protected extractValidationMessage(err: HttpErrorResponse): string | undefined {
        const error = err.error;
 
        if (typeof error === 'object' && error) {
            Eif ('errors' in error) {
                const errors = error.errors;
                if (Array.isArray(errors) && errors.length > 0 && typeof errors[0] === 'string') {
                    return errors[0];
                }
                Eif (typeof errors === 'object' && errors) {
                    const firstField = Object.keys(errors)[0];
                    Eif (firstField) {
                        const fieldErrors = (errors as Record<string, unknown>)[firstField];
                        Eif (Array.isArray(fieldErrors) && fieldErrors.length > 0) {
                            const firstFieldError = fieldErrors[0];
                            Eif (typeof firstFieldError === 'string' && firstFieldError.length > 0) {
                                return `${firstField}: ${firstFieldError}`;
                            }
                        }
                    }
                }
            }
        }
 
        return this.extractBackendMessage(err);
    }
}