1 | import isPlainObject from 'lodash/isPlainObject.js';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | export default function errorHandler(errorResponse) {
|
11 | const { config, response } = errorResponse;
|
12 | let errorName;
|
13 |
|
14 | if (config && config.headers && config.headers['Authorization']) {
|
15 | const token = `...${config.headers['Authorization'].toString().substr(-5)}`;
|
16 | config.headers['Authorization'] = `Bearer ${token}`;
|
17 | }
|
18 | if (!isPlainObject(response) || !isPlainObject(config)) {
|
19 | throw errorResponse;
|
20 | }
|
21 | const data = response?.data;
|
22 | const errorData = {
|
23 | status: response?.status,
|
24 | statusText: response?.statusText,
|
25 | message: '',
|
26 | details: {},
|
27 | };
|
28 | if (config && isPlainObject(config)) {
|
29 | errorData.request = {
|
30 | url: config.url,
|
31 | headers: config.headers,
|
32 | method: config.method,
|
33 | payloadData: config.data,
|
34 | };
|
35 | }
|
36 | if (data && typeof data === 'object') {
|
37 | if ('requestId' in data) {
|
38 | errorData.requestId = data.requestId || 'UNKNOWN';
|
39 | }
|
40 | if ('message' in data) {
|
41 | errorData.message = data.message || '';
|
42 | }
|
43 | if ('details' in data) {
|
44 | errorData.details = data.details || {};
|
45 | }
|
46 | errorName = data.sys?.id;
|
47 | }
|
48 | const error = new Error();
|
49 | error.name =
|
50 | errorName && errorName !== 'Unknown' ? errorName : `${response?.status} ${response?.statusText}`;
|
51 | try {
|
52 | error.message = JSON.stringify(errorData, null, ' ');
|
53 | }
|
54 | catch {
|
55 | error.message = errorData?.message ?? '';
|
56 | }
|
57 | throw error;
|
58 | }
|