-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathget-error-message.js
More file actions
36 lines (33 loc) · 1.13 KB
/
get-error-message.js
File metadata and controls
36 lines (33 loc) · 1.13 KB
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
/**
* Get error message from error object
* @param {Error} e - error object
* @param {?Object} [options] - options: {defaultMessage: string, withApiKey: {apiKey: string}}
* @param {?string} [options.fallbackMessage] - fallback error message
* @param {?Object} [options.withApiKey] - object with apiKey
* @param {?string} [options.withApiKey.apiKey] - apiKey
* @return {null|string}
*/
export const getErrorMessage = (e, options = {}) => {
const { fallbackMessage = 'Something went wrong.', withApiKey = null } = options;
const { apiKey } = withApiKey || {};
let message;
try {
// error is instance of ApiError
const error = e.getActualType();
if ((error.status === 401 || error.status === 403) && withApiKey) {
if (!apiKey) {
return null;
} else {
return 'Your API key is invalid. Please, set a new one.';
}
}
message = error.data?.status?.error || e.message || fallbackMessage;
} catch (err) {
// error is not instance of ApiError
message = e?.message || fallbackMessage;
}
if (!message || !message.trim()) {
message = fallbackMessage;
}
return message.trim();
};