File size: 2,082 Bytes
c7d34c1
 
e445b51
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1cfe1b
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
e445b51
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
b1cfe1b
 
 
 
 
 
 
 
 
c7d34c1
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
type Translate = (key: string, values?: Record<string, string | number>) => string;

export const superApiReferralUrl = 'https://gpt2image.superapi.buzz/';

export type ApiErrorSummary = {
    message: string;
    status?: number;
};

export type ApiErrorNotice = {
    message: string;
    links: Array<{
        label: string;
        url: string;
    }>;
};

export function buildUserFacingApiErrorMessage(options: ApiErrorSummary & { t: Translate }): string {
    const advice = buildApiErrorAdvice(options.status, options.t);
    if (!advice) return options.message;

    return options.t('error.apiFailedWithAdvice', {
        message: options.message,
        advice
    });
}

export function buildBatchPartialFailureMessage(options: {
    failed: number;
    total: number;
    errors: ApiErrorSummary[];
    t: Translate;
}): string {
    const reasons = options.errors
        .map(
            (error, index) =>
                `${index + 1}. ${buildUserFacingApiErrorMessage({
                    message: error.message,
                    status: error.status,
                    t: options.t
                })}`
        )
        .join(' ');

    return options.t('error.batchPartialFailureDetailed', {
        failed: options.failed,
        total: options.total,
        reasons
    });
}

export function buildApiErrorNotice(message: string): ApiErrorNotice {
    return { message, links: [] };
}

function buildApiErrorAdvice(status: number | undefined, t: Translate): string | null {
    if (status === 401 || status === 403) return t('error.adviceAuth');
    if (status === 429) return t('error.adviceRateLimit');
    if (status === 524) return t('error.adviceCloudflare', { url: superApiReferralUrl });
    if (isUpstreamStatus(status)) return t('error.adviceUpstream');
    return null;
}

function isUpstreamStatus(status: number | undefined): boolean {
    return (
        status === 500 ||
        status === 502 ||
        status === 503 ||
        status === 504 ||
        status === 520 ||
        status === 522 ||
        status === 523
    );
}