async function decodeErrorSafely()

in packages/graph-explorer/src/connector/fetchDatabaseRequest.ts [24:56]


async function decodeErrorSafely(response: Response): Promise<any> {
  const contentType = response.headers.get("Content-Type");
  const contentTypeHasValue = contentType !== null && contentType.length > 0;
  // Assume missing content type is JSON
  const isJson =
    !contentTypeHasValue || contentType.includes("application/json");

  // Extract the raw text from the response
  const rawText = await response.text();

  // Check for empty response
  if (!rawText) {
    return undefined;
  }

  if (isJson) {
    try {
      // Try parsing the response as JSON
      const data = JSON.parse(rawText);

      // Flatten the error if it contains an error object
      return data?.error ?? data;
    } catch (error) {
      console.error("Failed to decode the error response as JSON", {
        error,
        rawText,
      });
      return rawText;
    }
  }

  return { message: rawText };
}