-
Notifications
You must be signed in to change notification settings - Fork 1
/
ajax-error-parser.js
154 lines (134 loc) · 4.48 KB
/
ajax-error-parser.js
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
import {fireEvent} from './fire-custom-event.js';
const globalMessage = 'An error occurred. Please try again later.';
const httpStatus413Msg = 'The uploaded file is too large!';
const http403Msg = 'Forbidden action due to lack of permissions';
export function tryGetResponseError(response) {
if (response.status === 413) {
return httpStatus413Msg;
}
if (response.status == 403) {
return http403Msg;
}
if (response.status >= 401) {
return globalMessage;
}
return response.response || globalMessage;
}
/**
*
* @param errors
* @param keyTranslate - optional function to translate error keys
* @returns {string[]}
*/
export function getErrorsArray(errors, keyTranslate) {
if (!errors) {
return [];
}
if (typeof errors === 'string') {
return [translateSomeBkErrMessages(errors)];
}
if (!keyTranslate) {
keyTranslate = window.ajaxErrorParserTranslateFunction || defaultKeyTranslate;
}
if (Array.isArray(errors)) {
return errors
.map((error) =>
typeof error === 'string' ? translateSomeBkErrMessages(error) : getErrorsArray(error, keyTranslate)
)
.flat();
}
const isObject = typeof errors === 'object';
if (isObject && errors.error && typeof errors.error === 'string') {
return [translateSomeBkErrMessages(errors.error)];
}
if (isObject && errors.errors && Array.isArray(errors.errors)) {
return errors.errors
.map(function (err) {
if (typeof err === 'object') {
return Object.values(err); // will work only for strings
} else {
return err;
}
})
.flat();
}
if (isObject && errors.non_field_errors && Array.isArray(errors.non_field_errors)) {
return errors.non_field_errors;
}
if (isObject && errors.code) {
return parseTypedError(errors, keyTranslate);
} else if (isObject) {
return Object.entries(errors)
.map(([field, value]) => {
const translatedField = keyTranslate(field);
if (typeof value === 'string') {
return `${keyTranslate('Field')} ${translatedField} - ${translateSomeBkErrMessages(value)}`;
}
if (Array.isArray(value)) {
const baseText = `${keyTranslate('Field')} ${translatedField}: `;
const textErrors = getErrorsArray(value, keyTranslate);
// * The marking is used for display in etools-error-messages-box
// * and adds a welcomed identations when displayed as a toast message
return textErrors.length === 1 ? `${baseText}${textErrors}` : [baseText, ..._markNestedErrors(textErrors)];
}
if (typeof value === 'object') {
return Object.entries(value).map(
([nestedField, nestedValue]) =>
`${keyTranslate('Field')} ${translatedField} (${keyTranslate(nestedField)}) - ${getErrorsArray(
nestedValue,
keyTranslate
)}`
);
}
})
.flat();
}
return [];
}
function _markNestedErrors(errs) {
// @ts-ignore
return errs.map((er) => ' ' + er);
}
export function formatServerErrorAsText(error, keyTranslate) {
const errorResponse = tryGetResponseError(error);
const errorsArray = getErrorsArray(errorResponse, keyTranslate);
if (errorsArray && errorsArray.length) {
return errorsArray.join('\n');
}
return error;
}
export function parseRequestErrorsAndShowAsToastMsgs(error, source, redirectOn404 = false) {
if (redirectOn404 && error.status === 404) {
fireEvent(source, '404');
return;
}
const errorsString = formatServerErrorAsText(error);
showErrorAsToastMsg(errorsString, source);
}
export function showErrorAsToastMsg(errorsString, source) {
if (errorsString) {
fireEvent(source, 'toast', {text: errorsString, showCloseBtn: true});
}
}
function parseTypedError(errorObject, keyTranslate) {
switch (errorObject.code) {
case 'required_in_status':
const fields = errorObject.extra.fields.map((field) => keyTranslate(field)).join(', ');
return `${keyTranslate('required_in_status')}: ${fields}`;
default:
return errorObject.description || '';
}
}
export function defaultKeyTranslate(key = '') {
return key
.split('_')
.map((fieldPart) => `${fieldPart[0].toUpperCase()}${fieldPart.slice(1)}`)
.join(' ');
}
// Errors that come from unicef-attachements library are not translated on the BK (Feb 2023)
function translateSomeBkErrMessages(error) {
if (window.ajaxErrorParserTranslateFunction) {
return window.ajaxErrorParserTranslateFunction(error);
}
return error;
}