File size: 1,109 Bytes
ddce7e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export function getUpstreamStatus(error) {
  return error?.response?.status || error?.status || error?.statusCode || 500;
}

async function readReadableStreamToString(readable) {
  const chunks = [];
  for await (const chunk of readable) {
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString();
}

export async function readUpstreamErrorBody(error) {
  if (!error) return '';

  const data = error?.response?.data;

  // axios stream response
  if (data?.readable) {
    try {
      return await readReadableStreamToString(data);
    } catch {
      // fall through
    }
  }

  if (typeof data === 'object' && data !== null) {
    try {
      return JSON.stringify(data, null, 2);
    } catch {
      return String(data);
    }
  }

  if (data !== undefined && data !== null) return String(data);
  if (error.message) return String(error.message);
  return String(error);
}

export function isCallerDoesNotHavePermission(errorBody) {
  try {
    return JSON.stringify(errorBody).includes('The caller does not');
  } catch {
    return String(errorBody).includes('The caller does not');
  }
}